~ chicken-core (master) /manual/Module (scheme base)
Trap1[[tags: manual]]
2[[toc:]]
3
4== Module scheme
5
6This module provides all of CHICKEN's R7RS procedures and macros.
7These descriptions are based directly on the ''Revised^7 Report on the
8Algorithmic Language Scheme''.
9
10== Expressions
11
12Expression types are categorized as primitive or derived. Primitive
13expression types include variables and procedure calls. Derived
14expression types are not semantically primitive, but can instead be
15defined as macros. The distinction which R7RS makes between primitive
16and derived is unimportant and does not necessarily reflect how it is
17implemented in CHICKEN itself.
18
19=== Primitive expression types
20
21==== Variable references
22
23<macro><variable></macro><br>
24
25An expression consisting of a variable is a variable reference. The
26value of the variable reference is the value stored in the location to
27which the variable is bound. It is an error to reference an unbound
28variable.
29
30 (define x 28)
31 x ===> 28
32
33==== Literal expressions
34
35<macro>(quote <datum>)</macro><br>
36<macro>'<datum></macro><br>
37<macro><constant></macro><br>
38
39(quote <datum>) evaluates to <datum>. <Datum> may be any external
40representation of a Scheme object. This notation is used to include
41literal constants in Scheme code.
42
43 (quote a) ===> a
44 (quote #(a b c)) ===> #(a b c)
45 (quote (+ 1 2)) ===> (+ 1 2)
46
47(quote <datum>) may be abbreviated as '<datum>. The two notations are
48equivalent in all respects.
49
50 'a ===> a
51 '#(a b c) ===> #(a b c)
52 '() ===> ()
53 '(+ 1 2) ===> (+ 1 2)
54 '(quote a) ===> (quote a)
55 ''a ===> (quote a)
56
57Numerical constants, string constants, character constants, and boolean
58constants evaluate "to themselves"; they need not be quoted.
59
60 '"abc" ===> "abc"
61 "abc" ===> "abc"
62 '145932 ===> 145932
63 145932 ===> 145932
64 '#t ===> #t
65 #t ===> #t
66 '#(a 10) ===> #(a 10)
67 #(a 10) ===> #(a 10)
68 '#u8(64 65) ===> #u8(64 65)
69 #u8(64 65) ===> #u8(64 65)
70
71It is an error to alter a constant (i.e. the value of a literal
72expression) using a mutation procedure like set-car! or string-set!.
73In the current implementation of CHICKEN, identical constants don't
74share memory and it is possible to mutate them, but this may change in
75the future.
76
77==== Procedure calls
78
79<macro>(<operator> <operand[1]> ...)</macro><br>
80
81A procedure call is written by simply enclosing in parentheses
82expressions for the procedure to be called and the arguments to be
83passed to it. The operator and operand expressions are evaluated (in an
84unspecified order) and the resulting procedure is passed the resulting
85arguments.
86
87 (+ 3 4) ===> 7
88 ((if #f + *) 3 4) ===> 12
89
90A number of procedures are available as the values of variables in the
91initial environment; for example, the addition and multiplication
92procedures in the above examples are the values of the variables + and
93*. New procedures are created by evaluating lambda
94expressions. Procedure calls may return any number of values (see the
95{{values}} procedure [[#control-features|below]]).
96
97Procedure calls are also called combinations.
98
99Note: In contrast to other dialects of Lisp, the order of
100evaluation is unspecified, and the operator expression and the
101operand expressions are always evaluated with the same evaluation
102rules.
103
104Note: Although the order of evaluation is otherwise unspecified,
105the effect of any concurrent evaluation of the operator and operand
106expressions is constrained to be consistent with some sequential
107order of evaluation. The order of evaluation may be chosen
108differently for each procedure call.
109
110Note: In many dialects of Lisp, the empty combination, (), is a
111legitimate expression. In Scheme, combinations must have at least
112one subexpression, so () is not a syntactically valid expression.
113
114==== Procedures
115
116<macro>(lambda <formals> <body>)</macro><br>
117
118Syntax: <Formals> should be a formal arguments list as described below,
119and <body> should be a sequence of one or more expressions.
120
121Semantics: A lambda expression evaluates to a procedure. The
122environment in effect when the lambda expression was evaluated is
123remembered as part of the procedure. When the procedure is later called
124with some actual arguments, the environment in which the lambda
125expression was evaluated will be extended by binding the variables in
126the formal argument list to fresh locations, the corresponding actual
127argument values will be stored in those locations, and the expressions
128in the body of the lambda expression will be evaluated sequentially in
129the extended environment. The result(s) of the last expression in the
130body will be returned as the result(s) of the procedure call.
131
132 (lambda (x) (+ x x)) ===> a procedure
133 ((lambda (x) (+ x x)) 4) ===> 8
134
135 (define reverse-subtract
136 (lambda (x y) (- y x)))
137 (reverse-subtract 7 10) ===> 3
138
139 (define add4
140 (let ((x 4))
141 (lambda (y) (+ x y))))
142 (add4 6) ===> 10
143
144<Formals> should have one of the following forms:
145
146* (<variable[1]> ...): The procedure takes a fixed number of
147 arguments; when the procedure is called, the arguments will be
148 stored in the bindings of the corresponding variables.
149
150* <variable>: The procedure takes any number of arguments; when the
151 procedure is called, the sequence of actual arguments is converted
152 into a newly allocated list, and the list is stored in the binding
153 of the <variable>.
154
155* (<variable[1]> ... <variable[n]> . <variable[n+1]>): If a
156 space-delimited period precedes the last variable, then the
157 procedure takes n or more arguments, where n is the number of
158 formal arguments before the period (there must be at least one).
159 The value stored in the binding of the last variable will be a
160 newly allocated list of the actual arguments left over after all
161 the other actual arguments have been matched up against the other
162 formal arguments.
163
164It is an error for a <variable> to appear more than once in <formals>.
165
166 ((lambda x x) 3 4 5 6) ===> (3 4 5 6)
167 ((lambda (x y . z) z)
168 3 4 5 6) ===> (5 6)
169
170Each procedure created as the result of evaluating a lambda expression
171is (conceptually) tagged with a storage location, in order to make eqv?
172and eq? work on procedures.
173
174As an extension to R7RS, CHICKEN also supports "extended" DSSSL style
175parameter lists, which allows embedded special keywords. Such a
176keyword gives a special meaning to the {{<formal>}} it precedes.
177DSSSL parameter lists are defined by the following grammar:
178
179 <parameter-list> ==> <required-parameter>*
180 [#!optional <optional-parameter>*]
181 [#!rest <rest-parameter>]
182 [#!key <keyword-parameter>*]
183 <required-parameter> ==> <ident>
184 <optional-parameter> ==> <ident>
185 | (<ident> <initializer>)
186 <rest-parameter> ==> <ident>
187 <keyword-parameter> ==> <ident>
188 | (<ident> <initializer>)
189 <initializer> ==> <expr>
190
191When a procedure is applied to a list of arguments, the parameters and arguments are processed from left to right as follows:
192
193* Required-parameters are bound to successive arguments starting with the first argument. It shall be an error if there are fewer arguments than required-parameters.
194* Next, the optional-parameters are bound with the remaining arguments. If there are fewer arguments than optional-parameters, then the remaining optional-parameters are bound to the result of the evaluation of their corresponding <initializer>, if one was specified, otherwise {{#f}}. The corresponding <initializer> is evaluated in an environment in which all previous parameters have been bound.
195* If there is a rest-parameter, then it is bound to a list containing all the remaining arguments left over after the argument bindings with required-parameters and optional-parameters have been made.
196* If {{#!key}} was specified in the parameter-list, there should be an even number of remaining arguments. These are interpreted as a series of pairs, where the first member of each pair is a keyword specifying the parameter name, and the second member is the corresponding value. If the same keyword occurs more than once in the list of arguments, then the corresponding value of the first keyword is the binding value. If there is no argument for a particular keyword-parameter, then the variable is bound to the result of evaluating <initializer>, if one was specified, otherwise {{#f}}. The corresponding <initializer> is evaluated in an environment in which all previous parameters have been bound.
197
198Needing a special mention is the close relationship between the
199rest-parameter and possible keyword-parameters. Declaring a
200rest-parameter binds up all remaining arguments in a list, as
201described above. These same remaining arguments are also used for
202attempted matches with declared keyword-parameters, as described
203above, in which case a matching keyword-parameter binds to the
204corresponding value argument at the same time that both the keyword
205and value arguments are added to the rest parameter list. Note that
206for efficiency reasons, the keyword-parameter matching does nothing
207more than simply attempt to match with pairs that may exist in the
208remaining arguments. Extra arguments that don't match are simply
209unused and forgotten if no rest-parameter has been declared. Because
210of this, the caller of a procedure containing one or more
211keyword-parameters cannot rely on any kind of system error to report
212wrong keywords being passed in.
213
214It shall be an error for an {{<ident>}} to appear more than once in a
215parameter-list.
216
217If there is no rest-parameter and no keyword-parameters in the parameter-list, then it shall be an error for any extra arguments to be passed to the procedure.
218
219
220Example:
221
222 ((lambda x x) 3 4 5 6) => (3 4 5 6)
223 ((lambda (x y #!rest z) z)
224 3 4 5 6) => (5 6)
225 ((lambda (x y #!optional z #!rest r #!key i (j 1))
226 (list x y z i: i j: j))
227 3 4 5 i: 6 i: 7) => (3 4 5 i: 6 j: 1)
228
229
230
231==== Conditionals
232
233<macro>(if <test> <consequent> <alternate>)</macro><br>
234<macro>(if <test> <consequent>)</macro><br>
235
236Syntax: <Test>, <consequent>, and <alternate> may be arbitrary
237expressions.
238
239Semantics: An if expression is evaluated as follows: first, <test> is
240evaluated. If it yields a true value (see [[#Booleans|the section
241about booleans]] below), then <consequent> is evaluated and its
242value(s) is(are) returned. Otherwise <alternate> is evaluated and its
243value(s) is(are) returned. If <test> yields a false value and no
244<alternate> is specified, then the result of the expression is
245unspecified.
246
247 (if (> 3 2) 'yes 'no) ===> yes
248 (if (> 2 3) 'yes 'no) ===> no
249 (if (> 3 2)
250 (- 3 2)
251 (+ 3 2)) ===> 1
252
253==== Assignments
254
255<macro>(set! <variable> <expression>)</macro><br>
256
257<Expression> is evaluated, and the resulting value is stored in the
258location to which <variable> is bound. <Variable> must be bound either
259in some region enclosing the set! expression or at top level. The
260result of the set! expression is unspecified.
261
262 (define x 2)
263 (+ x 1) ===> 3
264 (set! x 4) ===> unspecified
265 (+ x 1) ===> 5
266
267As an extension to R7RS, {{set!}} for unbound toplevel variables is
268allowed. Also, {{(set! (PROCEDURE ...) ...)}} is supported, as CHICKEN
269implements [[http://srfi.schemers.org/srfi-17/srfi-17.html|SRFI-17]].
270
271==== Inclusion
272
273<macro>(include STRING1 STRING2 ...)</macro>
274<macro>(include-ci STRING1 STRING2 ...)</macro>
275
276Semantics: Both {{include}} and {{include-ci}} take one or
277more filenames expressed as string literals, apply an
278implementation-specific algorithm to find corresponding
279files, read the contents of the files in the specified order
280as if by repeated applications of {{read}}, and effectively replace the {{include}}
281or {{include-ci}} expression with a {{begin}}
282expression containing what was read from the files. The
283difference between the two is that {{include-ci}} reads each
284file as if it began with the {{#!fold-case}} directive, while
285{{include}} does not.
286
287
288=== Derived expression types
289
290The constructs in this section are hygienic. For reference purposes,
291these macro definitions will convert most of the constructs described
292in this section into the primitive constructs described in the
293previous section. This does not necessarily mean that's exactly how
294it's implemented in CHICKEN.
295
296==== Conditionals
297
298<macro>(cond <clause[1]> <clause[2]> ...)</macro><br>
299
300Syntax: Each <clause> should be of the form
301
302 (<test> <expression[1]> ...)
303
304where <test> is any expression. Alternatively, a <clause> may be of the
305form
306
307 (<test> => <expression>)
308
309The last <clause> may be an "else clause," which has the form
310
311 (else <expression[1]> <expression[2]> ...).
312
313Semantics: A cond expression is evaluated by evaluating the <test>
314expressions of successive <clause>s in order until one of them
315evaluates to a true value (see [[#Booleans|the section about
316booleans]] below). When a <test> evaluates to a true value, then the
317remaining <expression>s in its <clause> are evaluated in order, and
318the result(s) of the last <expression> in the <clause> is(are)
319returned as the result(s) of the entire cond expression. If the
320selected <clause> contains only the <test> and no <expression>s, then
321the value of the <test> is returned as the result. If the selected
322<clause> uses the => alternate form, then the <expression> is
323evaluated. Its value must be a procedure that accepts one argument;
324this procedure is then called on the value of the <test> and the
325value(s) returned by this procedure is(are) returned by the cond
326expression. If all <test>s evaluate to false values, and there is no
327else clause, then the result of the conditional expression is
328unspecified; if there is an else clause, then its <expression>s are
329evaluated, and the value(s) of the last one is(are) returned.
330
331 (cond ((> 3 2) 'greater)
332 ((< 3 2) 'less)) ===> greater
333 (cond ((> 3 3) 'greater)
334 ((< 3 3) 'less)
335 (else 'equal)) ===> equal
336 (cond ((assv 'b '((a 1) (b 2))) => cadr)
337 (else #f)) ===> 2
338
339
340As an extension to R7RS, CHICKEN also supports the
341[[http://srfi.schemers.org/srfi-61|SRFI-61]] syntax:
342
343 (<generator> <guard> => <expression>)
344
345In this situation, {{generator}} is ''always'' evaluated. Its
346resulting value(s) are used as argument(s) for the {{guard}}
347procedure. Finally, if {{guard}} returns a non-{{#f}} value, the
348{{expression}} is evaluated by calling it with the result of
349{{guard}}. Otherwise, evaluation procedes to the next clause.
350
351<macro>(case <key> <clause[1]> <clause[2]> ...)</macro><br>
352
353Syntax: <Key> may be any expression. Each <clause> should have the form
354
355 ((<datum[1]> ...) <expression[1]> <expression[2]> ...),
356
357where each <datum> is an external representation of some object.
358Alternatively, as per R7RS, a <clause> may be of the form
359
360 ((<datum[1]> ...) => <expression>).
361
362All the <datum>s must be distinct. The last <clause> may be an
363"else clause," which has one of the following two forms:
364
365 (else <expression[1]> <expression[2]> ...)
366 (else => <expression>).
367
368Semantics: A case expression is evaluated as follows. <Key> is
369evaluated and its result is compared against each <datum>. If the
370result of evaluating <key> is equivalent (in the sense of {{eqv?}};
371see [[#equivalence-predicates|below]]) to a <datum>, then the
372expressions in the corresponding <clause> are evaluated from left to
373right and the result(s) of the last expression in the <clause> is(are)
374returned as the result(s) of the case expression. If the selected
375<clause> uses the => alternate form (an R7RS extension), then the
376<expression> is evaluated. Its value must be a procedure that accepts
377one argument; this procedure is then called on the value of the <key>
378and the value(s) returned by this procedure is(are) returned by the
379case expression. If the result of evaluating <key> is different from
380every <datum>, then if there is an else clause its expressions are
381evaluated and the result(s) of the last is(are) the result(s) of the
382case expression; otherwise the result of the case expression is
383unspecified.
384
385 (case (* 2 3)
386 ((2 3 5 7) 'prime)
387 ((1 4 6 8 9) 'composite)) ===> composite
388 (case (car '(c d))
389 ((a) 'a)
390 ((b) 'b)) ===> unspecified
391 (case (car '(c d))
392 ((a e i o u) 'vowel)
393 ((w y) 'semivowel)
394 (else 'consonant)) ===> consonant
395
396<macro>(and <test[1]> ...)</macro><br>
397
398The <test> expressions are evaluated from left to right, and the value
399of the first expression that evaluates to a false value (see
400[[#Booleans|the section about booleans]]) is returned. Any remaining
401expressions are not evaluated. If all the expressions evaluate to true
402values, the value of the last expression is returned. If there are no
403expressions then #t is returned.
404
405 (and (= 2 2) (> 2 1)) ===> #t
406 (and (= 2 2) (< 2 1)) ===> #f
407 (and 1 2 'c '(f g)) ===> (f g)
408 (and) ===> #t
409
410<macro>(or <test[1]> ...)</macro><br>
411
412The <test> expressions are evaluated from left to right, and the value
413of the first expression that evaluates to a true value (see
414[[#Booleans|the section about booleans]]) is returned. Any remaining
415expressions are not evaluated. If all expressions evaluate to false
416values, the value of the last expression is returned. If there are no
417expressions then #f is returned.
418
419 (or (= 2 2) (> 2 1)) ===> #t
420 (or (= 2 2) (< 2 1)) ===> #t
421 (or #f #f #f) ===> #f
422 (or (memq 'b '(a b c))
423 (/ 3 0)) ===> (b c)
424
425<macro>(unless TEST EXP1 EXP2 ...)</macro>
426
427Equivalent to:
428
429<enscript highlight=scheme>
430(if (not TEST) (begin EXP1 EXP2 ...))
431</enscript>
432
433<macro>(when TEST EXP1 EXP2 ...)</macro>
434
435Equivalent to:
436
437<enscript highlight=scheme>
438(if TEST (begin EXP1 EXP2 ...))
439</enscript>
440
441<macro>(cond-expand <ce-clause1> <ce-clause2> ...)</macro>
442
443The {{cond-expand}} expression type provides a way
444to statically expand different expressions depending on the
445implementation. A <ce-clause> takes the following form:
446
447{{
448(<feature requirement> <expression> ...)
449}}
450
451The last clause can be an "else clause," which has the form
452
453{{
454(else <expression> ...)
455}}]
456
457A ⟨feature requirement⟩ takes one of the following forms:
458
459<feature identifier>
460
461{{(library <library name>)}}
462
463{{(and <feature requirement> ...)}}
464
465{{(or <feature requirement> ...)}}
466
467{{(not <feature requirement>)}}
468
469Each implementation maintains a list of
470feature identifiers which are present, as well as a list
471of libraries which can be imported.
472The value of a <feature requirement> is determined by replacing each
473<feature identifier> and {{(library <library name>)}} on the
474implementation’s lists with {{#t}}, and all other feature identifiers and library names with {{#f}}, then evaluating the resulting expression as a Scheme boolean expression under
475the normal interpretation of {{and}}, {{or}}, and {{not}}.
476
477A {{cond-expand}} is then expanded by evaluating the
478<feature requirement>s of successive <ce-clause>s in order
479until one of them returns {{#t}}. When a true clause is found,
480the corresponding <expression>s are expanded to a {{begin}},
481and the remaining clauses are ignored.
482
483If none of the
484<feature requirement>s evaluate to {{#t}}, then if there is an
485{{else}} clause, its <expression>s are included. Otherwise, the
486behavior of the {{cond}}-expand is unspecified. Unlike {{cond}},
487{{cond-expand}} does not depend on the value of any variables.
488
489The following features are built-in and always available by default:
490{{chicken}}, {{srfi-0}}, {{srfi-2}}, {{srfi-6}}, {{srfi-8}}, {{srfi-9}},
491{{srfi-11}}, {{srfi-12}}, {{srfi-15}}, {{srfi-16}}, {{srfi-17}}, {{srfi-23}},
492{{srfi-26}}, {{srfi-28}}, {{srfi-30}}, {{srfi-31}}, {{srfi-39}}, {{srfi-46}},
493{{srfi-55}}, {{srfi-61}}, {{srfi-62}}, {{srfi-87}}, {{srfi-88}}.
494
495There are also situation-specific feature identifiers: {{compiling}} during
496compilation, {{csi}} when running in the interpreter, and {{compiler-extension}}
497when running within the compiler.
498
499The symbols returned by the following procedures from
500[[Module (chicken platform)|(chicken platform)]] are also available
501as feature-identifiers in all situations: {{(machine-byte-order)}},
502{{(machine-type)}}, {{(software-type)}}, {{(software-version)}}. For
503example, the {{machine-type}} class of feature-identifiers include
504{{arm}}, {{alpha}}, {{mips}}, etc.
505
506Platform endianness is indicated by the {{little-endian}} and {{big-endian}}
507features.
508
509In addition the following feature-identifiers may exist: {{cross-chicken}},
510{{dload}}, {{gchooks}}, {{ptables}}, {{case-insensitive}}.
511
512
513==== Binding constructs
514
515The three binding constructs let, let*, and letrec give Scheme a block
516structure, like Algol 60. The syntax of the three constructs is
517identical, but they differ in the regions they establish for their
518variable bindings. In a let expression, the initial values are computed
519before any of the variables become bound; in a let* expression, the
520bindings and evaluations are performed sequentially; while in a letrec
521expression, all the bindings are in effect while their initial values
522are being computed, thus allowing mutually recursive definitions.
523
524<macro>(let <bindings> <body>)</macro><br>
525
526Syntax: <Bindings> should have the form
527
528 ((<variable[1]> <init[1]>) ...),
529
530where each <init> is an expression, and <body> should be a sequence of
531one or more expressions. It is an error for a <variable> to appear more
532than once in the list of variables being bound.
533
534Semantics: The <init>s are evaluated in the current environment (in
535some unspecified order), the <variable>s are bound to fresh locations
536holding the results, the <body> is evaluated in the extended
537environment, and the value(s) of the last expression of <body> is(are)
538returned. Each binding of a <variable> has <body> as its region.
539
540 (let ((x 2) (y 3))
541 (* x y)) ===> 6
542
543 (let ((x 2) (y 3))
544 (let ((x 7)
545 (z (+ x y)))
546 (* z x))) ===> 35
547
548See also "named let", [[#iteration|below]].
549
550<macro>(let* <bindings> <body>)</macro><br>
551
552Syntax: <Bindings> should have the form
553
554 ((<variable[1]> <init[1]>) ...),
555
556and <body> should be a sequence of one or more expressions.
557
558Semantics: Let* is similar to let, but the bindings are performed
559sequentially from left to right, and the region of a binding indicated
560by (<variable> <init>) is that part of the let* expression to the right
561of the binding. Thus the second binding is done in an environment in
562which the first binding is visible, and so on.
563
564 (let ((x 2) (y 3))
565 (let* ((x 7)
566 (z (+ x y)))
567 (* z x))) ===> 70
568
569<macro>(letrec <bindings> <body>)</macro><br>
570
571Syntax: <Bindings> should have the form
572
573 ((<variable[1]> <init[1]>) ...),
574
575and <body> should be a sequence of one or more expressions. It is an
576error for a <variable> to appear more than once in the list of
577variables being bound.
578
579Semantics: The <variable>s are bound to fresh locations holding
580undefined values, the <init>s are evaluated in the resulting
581environment (in some unspecified order), each <variable> is assigned to
582the result of the corresponding <init>, the <body> is evaluated in the
583resulting environment, and the value(s) of the last expression in
584<body> is(are) returned. Each binding of a <variable> has the entire
585letrec expression as its region, making it possible to define mutually
586recursive procedures.
587
588 (letrec ((even?
589 (lambda (n)
590 (if (zero? n)
591 #t
592 (odd? (- n 1)))))
593 (odd?
594 (lambda (n)
595 (if (zero? n)
596 #f
597 (even? (- n 1))))))
598 (even? 88))
599 ===> #t
600
601One restriction on letrec is very important: it must be possible to
602evaluate each <init> without assigning or referring to the value of any
603<variable>. If this restriction is violated, then it is an error. The
604restriction is necessary because Scheme passes arguments by value
605rather than by name. In the most common uses of letrec, all the <init>s
606are lambda expressions and the restriction is satisfied automatically.
607
608<macro>(letrec* <bindings> <body>) </macro>
609
610Syntax: <Bindings> has the form {{((<variable[1]> <init[1]>) ...)}},and
611<body>is a sequence of zero or more
612definitions followed by one or more expressions as described in section 4.1.4.
613It is an error for a <variable> to appear more than once in the list of
614variables being bound.
615
616Semantics: The <variable>s are bound to fresh locations, each <variable> is
617assigned in left-to-right order to the result of evaluating the corresponding
618<init> (interleaving evaluations and assignments), the <body> is evaluated in
619the resulting environment, and the values of the last expression in <body> are
620returned. Despite the left-to-right evaluation and assignment order, each
621binding of a <variable> has the entire letrec* expression as its region, making
622it possible to define mutually recursive procedures.
623
624If it is not possible to evaluate each <init> without assigning or referring to
625the value of the corresponding <variable> or the <variable> of any of the
626bindings that follow it in <bindings>, it is an error. Another restriction is
627that it is an error to invoke the continuation of an <init> more than once.
628
629{{
630;; Returns the arithmetic, geometric, and
631;; harmonic means of a nested list of numbers
632(define (means ton)
633 (letrec*
634 ((mean
635 (lambda (f g)
636 (f (/ (sum g ton) n))))
637 (sum
638 (lambda (g ton)
639 (if (null? ton)
640 (+)
641 (if (number? ton)
642 (g ton)
643 (+ (sum g (car ton))
644 (sum g (cdr ton)))))))
645 (n (sum (lambda (x) 1) ton)))
646 (values (mean values values)
647 (mean exp log)
648 (mean / /))))
649}}
650
651Evaluating {{(means '(3 (1 4)))}} returns three values: 8/3, 2.28942848510666
652(approximately), and 36/19.
653
654<macro>(let-values <mv binding spec> <body>)</macro>
655
656Syntax: <Mv binding spec> has the form {{((<formals[1]> <init[1]>) ...)}},
657where each <init> is an expression, and <body> is
658zero or more definitions followed by a sequence of one or more expressions as
659described in section 4.1.4. It is an error for a variable to appear more than
660once in the set of <formals>.
661
662Semantics: The <init>s are evaluated in the current environment (in some
663unspecified order) as if by invoking call-with-values, and the variables
664occurring in the <formals> are bound to fresh locations holding the values
665returned by the <init>s, where the <formals> are matched to the return values
666in the same way that the <formals> in a lambda expression are matched to the
667arguments in a procedure call. Then, the <body> is evaluated in the extended
668environment, and the values of the last expression of <body> are returned. Each
669binding of a <variable> has <body> as its region.
670
671It is an error if the <formals> do not match the number of values returned by
672the corresponding <init>.
673
674{{
675(let-values (((root rem) (exact-integer-sqrt 32)))
676 (* root rem)) ==> 35
677}}
678
679<macro>(let*-values <mv binding spec> <body>)</macro>
680
681Syntax: <Mv binding spec> has the form {{((<formals> <init>) ...)}},
682and <body> is a sequence of zero or more definitions
683followed by one or more expressions as described in section 4.1.4. In each
684<formals>, it is an error if any variable appears more than once.
685
686Semantics: The let*-values construct is similar to let-values, but the <init>s
687are evaluated and bindings created sequentially from left to right, with the
688region of the bindings of each <formals> including the <init>s to its right as
689well as <body>. Thus the second <init> is evaluated in an environment in which
690the first set of bindings is visible and initialized, and so on.
691
692{{
693(let ((a 'a) (b 'b) (x 'x) (y 'y))
694 (let*-values (((a b) (values x y))
695 ((x y) (values a b)))
696 (list a b x y))) ⟹ (x y x y)
697}}
698
699==== Sequencing
700
701<macro>(begin <expression[1]> <expression[2]> ...)</macro><br>
702
703The <expression>s are evaluated sequentially from left to right, and
704the value(s) of the last <expression> is(are) returned. This expression
705type is used to sequence side effects such as input and output.
706
707 (define x 0)
708
709 (begin (set! x 5)
710 (+ x 1)) ===> 6
711
712 (begin (display "4 plus 1 equals ")
713 (display (+ 4 1))) ===> unspecified
714 and prints 4 plus 1 equals 5
715
716As an extension to R7RS, CHICKEN also allows {{(begin)}} without body
717expressions in any context, not just at toplevel. This simply
718evaluates to the unspecified value.
719
720
721==== Iteration
722
723<macro>(do ((<variable[1]> <init[1]> <step[1]>) ...) (<test> <expression> ...) <command> ...)</macro><br>
724
725Do is an iteration construct. It specifies a set of variables to be
726bound, how they are to be initialized at the start, and how they are to
727be updated on each iteration. When a termination condition is met, the
728loop exits after evaluating the <expression>s.
729
730Do expressions are evaluated as follows: The <init> expressions are
731evaluated (in some unspecified order), the <variable>s are bound to
732fresh locations, the results of the <init> expressions are stored in
733the bindings of the <variable>s, and then the iteration phase begins.
734
735Each iteration begins by evaluating <test>; if the result is false
736(see [[#Booleans|the section about booleans]]), then the <command>
737expressions are evaluated in order for effect, the <step> expressions
738are evaluated in some unspecified order, the <variable>s are bound to
739fresh locations, the results of the <step>s are stored in the bindings
740of the <variable>s, and the next iteration begins.
741
742If <test> evaluates to a true value, then the <expression>s are
743evaluated from left to right and the value(s) of the last <expression>
744is(are) returned. If no <expression>s are present, then the value of
745the do expression is unspecified.
746
747The region of the binding of a <variable> consists of the entire do
748expression except for the <init>s. It is an error for a <variable> to
749appear more than once in the list of do variables.
750
751A <step> may be omitted, in which case the effect is the same as if
752(<variable> <init> <variable>) had been written instead of (<variable>
753<init>).
754
755 (do ((vec (make-vector 5))
756 (i 0 (+ i 1)))
757 ((= i 5) vec)
758 (vector-set! vec i i)) ===> #(0 1 2 3 4)
759
760 (let ((x '(1 3 5 7 9)))
761 (do ((x x (cdr x))
762 (sum 0 (+ sum (car x))))
763 ((null? x) sum))) ===> 25
764
765<macro>(let <variable> <bindings> <body>)</macro><br>
766
767"Named let" is a variant on the syntax of let which provides a more
768general looping construct than do and may also be used to express
769recursions. It has the same syntax and semantics as ordinary let except
770that <variable> is bound within <body> to a procedure whose formal
771arguments are the bound variables and whose body is <body>. Thus the
772execution of <body> may be repeated by invoking the procedure named by
773<variable>.
774
775 (let loop ((numbers '(3 -2 1 6 -5))
776 (nonneg '())
777 (neg '()))
778 (cond ((null? numbers) (list nonneg neg))
779 ((>= (car numbers) 0)
780 (loop (cdr numbers)
781 (cons (car numbers) nonneg)
782 neg))
783 ((< (car numbers) 0)
784 (loop (cdr numbers)
785 nonneg
786 (cons (car numbers) neg)))))
787 ===> ((6 1 3) (-5 -2))
788
789==== Dynamic bindings
790
791The dynamic extent of a procedure call is the time between when it is initiated
792and when it returns. In Scheme, {{call-with-current-continuation}}
793allows reentering a dynamic extent after its procedure call has returned. Thus,
794the dynamic extent of a call might not be a single, continuous time period.
795
796This sections introduces parameter objects, which can be bound to new values
797for the duration of a dynamic extent. The set of all parameter bindings at a
798given time is called the dynamic environment.
799
800<procedure>(make-parameter init [converter])</procedure>
801
802Returns a newly allocated parameter object, which is a procedure that accepts
803zero arguments and returns the value associated with the parameter object.
804Initially, this value is the value of {{(converter init)}}, or of {{init}}
805if the conversion procedure {{converter}} is not specified. The associated value can be temporarily changed
806using {{parameterize}}, which is described below.
807
808The effect of passing arguments to a parameter object is
809implementation-dependent.
810
811<macro>(parameterize ((<param[1]> <value[1]>) ...) <body>)</procedure>
812
813Syntax: Both <param[1]> and <value[1]> are expressions.
814
815It is an error if the value of any <param> expression is not a parameter
816object.
817
818Semantics: A parameterize expression is used to change the values returned by
819specified parameter objects during the evaluation of the body.
820
821The <param> and <value> expressions are evaluated in an unspecified order. The
822<body> is evaluated in a dynamic environment in which calls to the parameters
823return the results of passing the corresponding values to the conversion
824procedure specified when the parameters were created. Then the previous values
825of the parameters are restored without passing them to the conversion
826procedure. The results of the last expression in the <body> are returned as the
827results of the entire parameterize expression.
828
829 Note: If the conversion procedure is not idempotent, the results of
830 (parameterize ((x (x))) ...), which appears to bind the parameter
831
832 x to its current value, might not be what the user expects.
833
834If an implementation supports multiple threads of execution, then parameterize
835must not change the associated values of any parameters in any thread other
836than the current thread and threads created inside <body>.
837
838Parameter objects can be used to specify configurable settings for a
839computation without the need to pass the value to every procedure in the call
840chain explicitly.
841
842{{
843(define radix
844 (make-parameter
845 10
846 (lambda (x)
847 (if (and (exact-integer? x) (<= 2 x 16))
848 x
849 (error "invalid radix")))))
850
851(define (f n) (number->string n (radix)))
852
853(f 12) ==> "12"
854(parameterize ((radix 2))
855 (f 12)) ==> "1100"
856(f 12) ==> "12"
857
858(radix 16) ==> unspecified
859
860(parameterize ((radix 0))
861 (f 12)) ==> error
862}}
863
864==== Exception handling
865
866<macro>(guard (<variable> <cond clause[1]> <cond clause[2]> ...) <body>)</macro>
867
868Syntax: Each <cond clause> is as in the specification of cond.
869
870Semantics: The <body> is evaluated with an exception handler that binds the
871raised object (see {{raise}}) to <variable> and, within the scope
872of that binding, evaluates the clauses as if they were the clauses of a cond
873expression. That implicit cond expression is evaluated with the continuation
874and dynamic environment of the guard expression. If every <cond clause>'s
875<test> evaluates to #f and there is no else clause, then raise-continuable is
876invoked on the raised object within the dynamic environment of the original
877call to raise or raise-continuable, except that the current exception handler
878is that of the guard expression.
879
880{{
881(guard (condition
882 ((assq 'a condition) => cdr)
883 ((assq 'b condition)))
884 (raise (list (cons 'a 42))))
885==> 42
886
887(guard (condition
888 ((assq 'a condition) => cdr)
889 ((assq 'b condition)))
890 (raise (list (cons 'b 23))))
891==> (b . 23)
892}}
893
894==== Quasiquotation
895
896<macro>(quasiquote <qq template>)</macro><br>
897<macro>`<qq template></macro><br>
898
899"Backquote" or "quasiquote" expressions are useful for constructing
900a list or vector structure when most but not all of the desired
901structure is known in advance. If no commas appear within the <qq
902template>, the result of evaluating `<qq template> is equivalent to the
903result of evaluating '<qq template>. If a comma appears within the <qq
904template>, however, the expression following the comma is evaluated
905("unquoted") and its result is inserted into the structure instead of
906the comma and the expression. If a comma appears followed immediately
907by an at-sign (@), then the following expression must evaluate to a
908list; the opening and closing parentheses of the list are then
909"stripped away" and the elements of the list are inserted in place of
910the comma at-sign expression sequence. A comma at-sign should only
911appear within a list or vector <qq template>.
912
913 `(list ,(+ 1 2) 4) ===> (list 3 4)
914 (let ((name 'a)) `(list ,name ',name))
915 ===> (list a (quote a))
916 `(a ,(+ 1 2) ,@(map abs '(4 -5 6)) b)
917 ===> (a 3 4 5 6 b)
918 `(( foo ,(- 10 3)) ,@(cdr '(c)) . ,(car '(cons)))
919 ===> ((foo 7) . cons)
920 `#(10 5 ,(sqrt 4) ,@(map sqrt '(16 9)) 8)
921 ===> #(10 5 2 4 3 8)
922
923Quasiquote forms may be nested. Substitutions are made only for
924unquoted components appearing at the same nesting level as the
925outermost backquote. The nesting level increases by one inside each
926successive quasiquotation, and decreases by one inside each
927unquotation.
928
929 `(a `(b ,(+ 1 2) ,(foo ,(+ 1 3) d) e) f)
930 ===> (a `(b ,(+ 1 2) ,(foo 4 d) e) f)
931 (let ((name1 'x)
932 (name2 'y))
933 `(a `(b ,,name1 ,',name2 d) e))
934 ===> (a `(b ,x ,'y d) e)
935
936The two notations `<qq template> and (quasiquote <qq template>) are
937identical in all respects. ,<expression> is identical to (unquote
938<expression>), and ,@<expression> is identical to (unquote-splicing
939<expression>). The external syntax generated by write for two-element
940lists whose car is one of these symbols may vary between
941implementations.
942
943 (quasiquote (list (unquote (+ 1 2)) 4))
944 ===> (list 3 4)
945 '(quasiquote (list (unquote (+ 1 2)) 4))
946 ===> `(list ,(+ 1 2) 4)
947 i.e., (quasiquote (list (unquote (+ 1 2)) 4))
948
949Unpredictable behavior can result if any of the symbols quasiquote,
950unquote, or unquote-splicing appear in positions within a <qq template>
951otherwise than as described above.
952
953=== Macros
954
955Scheme programs can define and use new derived expression types, called
956macros. Program-defined expression types have the syntax
957
958 (<keyword> <datum> ...)
959
960where <keyword> is an identifier that uniquely determines the
961expression type. This identifier is called the syntactic keyword, or
962simply keyword, of the macro. The number of the <datum>s, and their
963syntax, depends on the expression type.
964
965Each instance of a macro is called a use of the macro. The set of rules
966that specifies how a use of a macro is transcribed into a more
967primitive expression is called the transformer of the macro.
968
969The macro definition facility consists of two parts:
970
971* A set of expressions used to establish that certain identifiers are
972 macro keywords, associate them with macro transformers, and control
973 the scope within which a macro is defined, and
974
975* a pattern language for specifying macro transformers.
976
977The syntactic keyword of a macro may shadow variable bindings, and
978local variable bindings may shadow keyword bindings. All macros defined
979using the pattern language are "hygienic" and "referentially
980transparent" and thus preserve Scheme's lexical scoping:
981
982* If a macro transformer inserts a binding for an identifier
983 (variable or keyword), the identifier will in effect be renamed
984 throughout its scope to avoid conflicts with other identifiers.
985 Note that a define at top level may or may not introduce a binding;
986 this depends on whether the binding already existed before (in which
987 case its value will be overridden).
988
989* If a macro transformer inserts a free reference to an identifier,
990 the reference refers to the binding that was visible where the
991 transformer was specified, regardless of any local bindings that
992 may surround the use of the macro.
993
994==== Binding constructs for syntactic keywords
995
996Let-syntax and letrec-syntax are analogous to let and letrec, but they
997bind syntactic keywords to macro transformers instead of binding
998variables to locations that contain values. Syntactic keywords may also
999be bound at top level.
1000
1001<macro>(let-syntax <bindings> <body>)</macro><br>
1002
1003Syntax: <Bindings> should have the form
1004
1005 ((<keyword> <transformer spec>) ...)
1006
1007Each <keyword> is an identifier, each <transformer spec> is an instance
1008of syntax-rules, and <body> should be a sequence of one or more
1009expressions. It is an error for a <keyword> to appear more than once in
1010the list of keywords being bound.
1011
1012Semantics: The <body> is expanded in the syntactic environment obtained
1013by extending the syntactic environment of the let-syntax expression
1014with macros whose keywords are the <keyword>s, bound to the specified
1015transformers. Each binding of a <keyword> has <body> as its region.
1016
1017 (let-syntax ((when (syntax-rules ()
1018 ((when test stmt1 stmt2 ...)
1019 (if test
1020 (begin stmt1
1021 stmt2 ...))))))
1022 (let ((if #t))
1023 (when if (set! if 'now))
1024 if)) ===> now
1025
1026 (let ((x 'outer))
1027 (let-syntax ((m (syntax-rules () ((m) x))))
1028 (let ((x 'inner))
1029 (m)))) ===> outer
1030
1031<macro>(letrec-syntax <bindings> <body>)</macro><br>
1032
1033Syntax: Same as for let-syntax.
1034
1035Semantics: The <body> is expanded in the syntactic environment obtained
1036by extending the syntactic environment of the letrec-syntax expression
1037with macros whose keywords are the <keyword>s, bound to the specified
1038transformers. Each binding of a <keyword> has the <bindings> as well as
1039the <body> within its region, so the transformers can transcribe
1040expressions into uses of the macros introduced by the letrec-syntax
1041expression.
1042
1043 (letrec-syntax
1044 ((my-or (syntax-rules ()
1045 ((my-or) #f)
1046 ((my-or e) e)
1047 ((my-or e1 e2 ...)
1048 (let ((temp e1))
1049 (if temp
1050 temp
1051 (my-or e2 ...)))))))
1052 (let ((x #f)
1053 (y 7)
1054 (temp 8)
1055 (let odd?)
1056 (if even?))
1057 (my-or x
1058 (let temp)
1059 (if y)
1060 y))) ===> 7
1061
1062==== Pattern language
1063
1064A <transformer spec> has the following form:
1065
1066 (syntax-rules <literals> <syntax rule> ...)
1067
1068Syntax: <Literals> is a list of identifiers and each <syntax rule>
1069should be of the form
1070
1071 (<pattern> <template>)
1072
1073The <pattern> in a <syntax rule> is a list <pattern> that begins with
1074the keyword for the macro.
1075
1076A <pattern> is either an identifier, a constant, or one of the
1077following
1078
1079 (<pattern> ...)
1080 (<pattern> <pattern> ... . <pattern>)
1081 (<pattern> ... <pattern> <ellipsis> <pattern> ...)
1082 #(<pattern> ...)
1083 #(<pattern> ... <pattern> <ellipsis>)
1084
1085and a template is either an identifier, a constant, or one of the
1086following
1087
1088 (<element> ...)
1089 (<element> <element> ... . <template>)
1090 (<ellipsis> <template>)
1091 #(<element> ...)
1092
1093where an <element> is a <template> optionally followed by an <ellipsis>
1094and an <ellipsis> is the identifier "...".
1095
1096Semantics: An instance of syntax-rules produces a new macro transformer
1097by specifying a sequence of hygienic rewrite rules. A use of a macro
1098whose keyword is associated with a transformer specified by
1099syntax-rules is matched against the patterns contained in the <syntax
1100rule>s, beginning with the leftmost <syntax rule>. When a match is
1101found, the macro use is transcribed hygienically according to the
1102template.
1103
1104An identifier appearing within a <pattern> can be an underscore ({{_}}), a literal
1105identifier listed in the list of <pattern literal>s, or the <ellipsis>. All
1106other identifiers appearing within a <pattern> are pattern variables.
1107
1108The keyword at the beginning of the pattern in a <syntax rule> is not involved
1109in the matching and is considered neither a pattern variable nor a literal
1110identifier.
1111
1112Pattern variables match arbitrary input elements and are used to refer to
1113elements of the input in the template. It is an error for the same pattern
1114variable to appear more than once in a <pattern>.
1115
1116Underscores also match arbitrary input elements but are not pattern variables
1117and so cannot be used to refer to those elements. If an underscore appears in
1118the <pattern literal>s list, then that takes precedence and underscores in the
1119<pattern> match as literals. Multiple underscores can appear in a <pattern>.
1120
1121Identifiers that appear in (<pattern literal> …) are interpreted as literal
1122identifiers to be matched against corresponding elements of the input. An
1123element in the input matches a literal identifier if and only if it is an
1124identifier and either both its occurrence in the macro expression and its
1125occurrence in the macro definition have the same lexical binding, or the two
1126identifiers are the same and both have no lexical binding.
1127
1128A subpattern followed by <ellipsis> can match zero or more elements of the
1129input, unless <ellipsis> appears in the <pattern literal>s, in which case it is
1130matched as a literal.
1131
1132More formally, an input form F matches a pattern P if and only if:
1133
1134* P is an underscore (_).
1135
1136* P is a non-literal identifier; or
1137
1138* P is a literal identifier and F is an identifier with the same
1139 binding; or
1140
1141* P is a list (P[1] ... P[n]) and F is a list of n forms that match P
1142 [1] through P[n], respectively; or
1143
1144* P is an improper list (P[1] P[2] ... P[n] . P[n+1]) and F is a list
1145 or improper list of n or more forms that match P[1] through P[n],
1146 respectively, and whose nth "cdr" matches P[n+1]; or
1147
1148* P is of the form (P[1] … P[k] P[e] <ellipsis> P[m+1] ... P[n] . P[x]) where E
1149 is a list or improper list of n elements, the first k of which match P[1]
1150 through P[k], whose next m−k elements each match P[e], whose remaining n−m
1151 elements match P[m+1] through P[n], and whose nth and final cdr matches P[x
1152 ]; or
1153
1154* P is a vector of the form #(P[1] ... P[n]) and F is a vector of n
1155 forms that match P[1] through P[n]; or
1156
1157 • P is of the form #(P[1] ... P[k] P[e] <ellipsis> P[m+1] ... P[n]) where E is a
1158 vector of n elements the first k of which match P[1] through P[k], whose
1159 next m−k elements each match P[e], and whose remaining n−m elements match P
1160 [m+1] through P[n]; or
1161
1162* P is a datum and F is equal to P in the sense of the equal?
1163 procedure.
1164
1165It is an error to use a macro keyword, within the scope of its binding,
1166in an expression that does not match any of the patterns.
1167
1168When a macro use is transcribed according to the template of the matching
1169<syntax rule>, pattern variables that occur in the template are replaced by the
1170elements they match in the input. Pattern variables that occur in subpatterns
1171followed by one or more instances of the identifier <ellipsis> are allowed only
1172in subtemplates that are followed by as many instances of <ellipsis>. They are
1173replaced in the output by all of the elements they match in the input,
1174distributed as indicated. It is an error if the output cannot be built up as
1175specified.
1176
1177Identifiers that appear in the template but are not pattern variables or the
1178identifier <ellipsis> are inserted into the output as literal identifiers. If a
1179literal identifier is inserted as a free identifier then it refers to the
1180binding of that identifier within whose scope the instance of syntax-rules
1181appears. If a literal identifier is inserted as a bound identifier then it is
1182in effect renamed to prevent inadvertent captures of free identifiers.
1183
1184A template of the form (<ellipsis> <template>) is identical to <template>,
1185except that ellipses within the template have no special meaning. That is, any
1186ellipses contained within <template> are treated as ordinary identifiers. In
1187particular, the template (<ellipsis> <ellipsis>) produces a single <ellipsis>.
1188This allows syntactic abstractions to expand into code containing ellipses.
1189
1190{{
1191(define-syntax be-like-begin
1192 (syntax-rules ()
1193 ((be-like-begin name)
1194 (define-syntax name
1195 (syntax-rules ()
1196 ((name expr (... ...))
1197 (begin expr (... ...))))))))
1198
1199(be-like-begin sequence)
1200
1201(sequence 1 2 3 4) ==> 4
1202}}
1203
1204As an example, if {{let}} and {{cond}} have their standard meaning
1205then they are hygienic (as required) and the following is not an
1206error.
1207
1208 (let ((=> #f))
1209 (cond (#t => 'ok))) ===> ok
1210
1211The macro transformer for cond recognizes => as a local variable, and
1212hence an expression, and not as the top-level identifier =>, which the
1213macro transformer treats as a syntactic keyword. Thus the example
1214expands into
1215
1216 (let ((=> #f))
1217 (if #t (begin => 'ok)))
1218
1219instead of
1220
1221 (let ((=> #f))
1222 (let ((temp #t))
1223 (if temp ('ok temp))))
1224
1225which would result in an invalid procedure call.
1226
1227==== Signaling errors in macro transformers
1228
1229<macro>(syntax-error <message> <args> ...)</macro>
1230
1231{{syntax-error}} behaves similarly to {{error}} except that implementations with
1232an expansion pass separate from evaluation should signal an error as soon as
1233{{syntax-error}} is expanded. This can be used as a syntax-rules <template> for a
1234<pattern> that is an invalid use of the macro, which can provide more
1235descriptive error messages. <message> is a string literal, and <args> arbitrary
1236expressions providing additional information. Applications cannot count on
1237being able to catch syntax errors with exception handlers or guards.
1238
1239 (define-syntax simple-let
1240 (syntax-rules ()
1241 ((_ (head ... ((x . y) val) . tail)
1242 body1 body2 ...)
1243 (syntax-error
1244 "expected an identifier but got"
1245 (x . y)))
1246 ((_ ((name val) ...) body1 body2 ...)
1247 ((lambda (name ...) body1 body2 ...)
1248 val ...))))
1249
1250
1251== Program structure
1252
1253=== Programs
1254
1255A Scheme program consists of a sequence of expressions, definitions,
1256and syntax definitions. Expressions are described in chapter 4;
1257definitions and syntax definitions are the subject of the rest of the
1258present chapter.
1259
1260Programs are typically stored in files or entered interactively to a
1261running Scheme system, although other paradigms are possible;
1262questions of user interface lie outside the scope of this
1263report. (Indeed, Scheme would still be useful as a notation for
1264expressing computational methods even in the absence of a mechanical
1265implementation.)
1266
1267Definitions and syntax definitions occurring at the top level of a
1268program can be interpreted declaratively. They cause bindings to be
1269created in the top level environment or modify the value of existing
1270top-level bindings. Expressions occurring at the top level of a
1271program are interpreted imperatively; they are executed in order when
1272the program is invoked or loaded, and typically perform some kind of
1273initialization.
1274
1275At the top level of a program (begin <form1> ...) is equivalent to the
1276sequence of expressions, definitions, and syntax definitions that form
1277the body of the begin.
1278
1279=== Import declarations
1280
1281<macro>(import IMPORT-SET ...)</macro>
1282
1283An import declaration provides a way to import identifiers exported by a
1284library. Each <import set> names a set of bindings from a library and possibly
1285specifies local names for the imported bindings. It takes one of the following
1286forms:
1287
1288* <library name>
1289
1290* {{(only <import set> <identifier> ...)}}
1291
1292* {{(except <import set> <identifier> ...)}}
1293
1294* {{(prefix <import set> <identifier>)}}
1295
1296* {{(rename <import set> (<identifier[1]> <identifier[2]>) ...)}}
1297
1298In the first form, all of the identifiers in the named library’s export clauses
1299are imported with the same names (or the exported names if exported with rename
1300). The additional <import set> forms modify this set as follows:
1301
1302* only produces a subset of the given <import set> including only the listed
1303 identifiers (after any renaming). It is an error if any of the listed
1304 identifiers are not found in the original set.
1305
1306* except produces a subset of the given <import set>, excluding the listed
1307 identifiers (after any renaming). It is an error if any of the listed
1308 identifiers are not found in the original set.
1309
1310* rename modifies the given <import set>, replacing each instance of
1311 <identifier[1]> with <identifier[2]>. It is an error if any of the listed
1312 <identifier[1]>s are not found in the original set.
1313
1314* prefix automatically renames all identifiers in the given <import set>,
1315 prefixing each with the specified <identifier>.
1316
1317=== Definitions
1318
1319Definitions are valid in some, but not all, contexts where expressions
1320are allowed. They are valid only at the top level of a <program> and
1321at the beginning of a <body>.
1322
1323A definition should have one of the following forms:
1324
1325<macro>(define <variable> <expression>)</macro><br>
1326<macro>(define (<variable> <formals>) <body>)</macro><br>
1327
1328<Formals> should be either a sequence of zero or more variables, or a
1329sequence of one or more variables followed by a space-delimited period
1330and another variable (as in a lambda expression). This form is
1331equivalent to
1332
1333 (define <variable>
1334 (lambda (<formals>) <body>)).
1335
1336<macro>(define <variable>)</macro>
1337
1338This form is a CHICKEN extension to R7RS, and is equivalent to
1339
1340 (define <variable> (void))
1341
1342<macro>(define (<variable> . <formal>) <body>)</macro><br>
1343
1344<Formal> should be a single variable. This form is equivalent to
1345
1346 (define <variable>
1347 (lambda <formal> <body>)).
1348
1349<macro>(define ((<variable> <formal> ...) ...) <body>)</macro><br>
1350
1351As an extension to R7RS, CHICKEN allows ''curried'' definitions, where
1352the variable name may also be a list specifying a name and a nested
1353lambda list. For example,
1354
1355 (define ((make-adder x) y) (+ x y))
1356
1357is equivalent to
1358
1359 (define (make-adder x) (lambda (y) (+ x y))).
1360
1361This type of curried definition can be nested arbitrarily and combined
1362with dotted tail notation or DSSSL keywords.
1363
1364==== Top level definitions
1365
1366At the top level of a program, a definition
1367
1368 (define <variable> <expression>)
1369
1370has essentially the same effect as the assignment expression
1371
1372 (set! <variable> <expression>)
1373
1374if <variable> is bound. If <variable> is not bound, however, then the
1375definition will bind <variable> to a new location before performing
1376the assignment, whereas it would be an error to perform a set! on an
1377unbound variable in standard Scheme. In CHICKEN, {{set!}} at toplevel
1378has the same effect as a definition, unless inside a module, in which
1379case it is an error.
1380
1381 (define add3
1382 (lambda (x) (+ x 3)))
1383 (add3 3) ===> 6
1384 (define first car)
1385 (first '(1 2)) ===> 1
1386
1387Some implementations of Scheme use an initial environment in which all
1388possible variables are bound to locations, most of which contain
1389undefined values. Top level definitions in such an implementation are
1390truly equivalent to assignments. In CHICKEN, attempting to evaluate
1391an unbound identifier will result in an error, but you ''can'' use
1392{{set!}} to bind an initial value to it.
1393
1394==== Internal definitions
1395
1396Definitions may occur at the beginning of a <body> (that is, the body
1397of a lambda, let, let*, letrec, let-syntax, or letrec-syntax
1398expression or that of a definition of an appropriate form). Such
1399definitions are known as internal definitions as opposed to the top
1400level definitions described above. The variable defined by an internal
1401definition is local to the <body>. That is, <variable> is bound rather
1402than assigned, and the region of the binding is the entire <body>. For
1403example,
1404
1405 (let ((x 5))
1406 (define foo (lambda (y) (bar x y)))
1407 (define bar (lambda (a b) (+ (* a b) a)))
1408 (foo (+ x 3))) ===> 45
1409
1410A <body> containing internal definitions can always be converted into
1411a completely equivalent letrec expression. For example, the let
1412expression in the above example is equivalent to
1413
1414 (let ((x 5))
1415 (letrec ((foo (lambda (y) (bar x y)))
1416 (bar (lambda (a b) (+ (* a b) a))))
1417 (foo (+ x 3))))
1418
1419Just as for the equivalent letrec expression, it must be possible to
1420evaluate each <expression> of every internal definition in a <body>
1421without assigning or referring to the value of any <variable> being
1422defined.
1423
1424Wherever an internal definition may occur (begin <definition1> ...) is
1425equivalent to the sequence of definitions that form the body of the
1426begin.
1427
1428CHICKEN extends the R7RS semantics by allowing internal definitions
1429everywhere, and not only at the beginning of a body. A set of internal
1430definitions is equivalent to a {{letrec}} form enclosing all following
1431expressions in the body:
1432
1433 (let ((foo 123))
1434 (bar)
1435 (define foo 456)
1436 (baz foo) )
1437
1438expands into
1439
1440 (let ((foo 123))
1441 (bar)
1442 (letrec ((foo 456))
1443 (baz foo) ) )
1444
1445Local sequences of {{define-syntax}} forms are translated into
1446equivalent {{letrec-syntax}} forms that enclose the following forms as
1447the body of the expression.
1448
1449=== Multiple-value definitions
1450
1451Another kind of definition is provided by define-values, which creates multiple
1452definitions from a single expression returning multiple values. It is allowed
1453wherever define is allowed.
1454
1455<macro>(define-values <formals> <expression>)</macro>
1456
1457It is an error if a variable appears more than once in the set of <formals>.
1458
1459Semantics: <Expression> is evaluated, and the <formals> are bound to the return
1460values in the same way that the <formals> in a lambda expression are matched to
1461the arguments in a procedure call.
1462
1463{{
1464(define-values (x y) (exact-integer-sqrt 17))
1465(list x y) ==> (4 1)
1466
1467(let ()
1468 (define-values (x y) (values 1 2))
1469 (+ x y)) ==> 3
1470}}
1471
1472=== Syntax definitions
1473
1474Syntax definitions are valid only at the top level of a
1475<program>. They have the following form:
1476
1477<macro>(define-syntax <keyword> <transformer spec>)</macro>
1478
1479{{<Keyword>}} is an identifier, and the {{<transformer spec>}} should
1480be an instance of {{syntax-rules}}. Note that CHICKEN also supports
1481{{er-macro-transformer}} and {{ir-macro-transformer}} here. For more
1482information see [[Module (chicken syntax)|the (chicken syntax) module]].
1483
1484The top-level syntactic environment is extended by binding the
1485<keyword> to the specified transformer.
1486
1487In standard Scheme, there is no define-syntax analogue of internal
1488definitions in, but CHICKEN allows these as an extension to the
1489standard. This means {{define-syntax}} may be used to define local
1490macros that are visible throughout the rest of the body in which the
1491definition occurred, i.e.
1492
1493 (let ()
1494 ...
1495 (define-syntax foo ...)
1496 (define-syntax bar ...)
1497 ...)
1498
1499is expanded into
1500
1501 (let ()
1502 ...
1503 (letrec-syntax ((foo ...) (bar ...))
1504 ...) )
1505
1506{{syntax-rules}} supports [[http://srfi.schemers.org/srfi-46/|SRFI-46]]
1507in allowing the ellipsis identifier to be user-defined by passing it as the first
1508argument to the {{syntax-rules}} form. Also, "tail" patterns of the form
1509
1510 (syntax-rules ()
1511 ((_ (a b ... c)
1512 ...
1513
1514are supported.
1515
1516The effect of destructively modifying the s-expression passed to a
1517transformer procedure is undefined.
1518
1519Although macros may expand into definitions and syntax definitions in
1520any context that permits them, it is an error for a definition or
1521syntax definition to shadow a syntactic keyword whose meaning is
1522needed to determine whether some form in the group of forms that
1523contains the shadowing definition is in fact a definition, or, for
1524internal definitions, is needed to determine the boundary between the
1525group and the expressions that follow the group. For example, the
1526following are errors:
1527
1528 (define define 3)
1529
1530 (begin (define begin list))
1531
1532 (let-syntax
1533 ((foo (syntax-rules ()
1534 ((foo (proc args ...) body ...)
1535 (define proc
1536 (lambda (args ...)
1537 body ...))))))
1538 (let ((x 3))
1539 (foo (plus x y) (+ x y))
1540 (define foo x)
1541 (plus foo x)))
1542
1543=== Record-type definitions
1544
1545Record-type definitions are used to introduce new data types, called record
1546types. Like other definitions, they can appear either at the outermost level or
1547in a body. The values of a record type are called records and are aggregations
1548of zero or more fields, each of which holds a single location. A predicate, a
1549constructor, and field accessors and mutators are defined for each record type.
1550
1551<macro>(define-record-type <name> <constructor> <pred> <field> ...)</macro>
1552
1553Syntax: <name> and <pred> are identifiers. The <constructor> is of the form
1554{{(<constructor name> <field name> ...)}} and each <field> is either of the form
1555{{(<field name> <accessor name>)}} or of the form {{(<field name> <accessor name> <modifier name>)}}. It is an error for the same identifier to occur more than once
1556as a field name. It is also an error for the same identifier to occur more than
1557once as an accessor or mutator name.
1558
1559The define-record-type construct is generative: each use creates a new record
1560type that is distinct from all existing types, including Scheme’s predefined
1561types and other record types — even record types of the same name or structure.
1562
1563An instance of define-record-type is equivalent to the following definitions:
1564
1565* <name> is bound to a representation of the record type itself. This may be
1566 a run-time object or a purely syntactic representation. The representation
1567 is not utilized in this report, but it serves as a means to identify the
1568 record type for use by further language extensions.
1569
1570* <constructor name> is bound to a procedure that takes as many arguments as
1571 there are <field name>s in the {{(<constructor name> ...)}} subexpression and
1572 returns a new record of type <name>. Fields whose names are listed with
1573 <constructor name> have the corresponding argument as their initial value.
1574 The initial values of all other fields are unspecified. It is an error for
1575 a field name to appear in <constructor> but not as a <field name>.
1576
1577* <pred> is bound to a predicate that returns #t when given a value returned
1578 by the procedure bound to <constructor name> and #f for everything else.
1579
1580* Each <accessor name> is bound to a procedure that takes a record of type
1581 <name> and returns the current value of the corresponding field. It is an
1582 error to pass an accessor a value which is not a record of the appropriate
1583 type.
1584
1585* Each <modifier name> is bound to a procedure that takes a record of type
1586 <name> and a value which becomes the new value of the corresponding field;
1587 an unspecified value is returned. It is an error to pass a modifier a first
1588 argument which is not a record of the appropriate type.
1589
1590For instance, the following record-type definition
1591
1592{{
1593(define-record-type <pare>
1594 (kons x y)
1595 pare?
1596 (x kar set-kar!)
1597 (y kdr))
1598}}
1599
1600defines kons to be a constructor, kar and kdr to be accessors, set-kar! to be a
1601modifier, and pare? to be a predicate for instances of <pare>.
1602
1603{{
1604(pare? (kons 1 2)) ⟹ #t
1605 (pare? (cons 1 2)) ⟹ #f
1606 (kar (kons 1 2)) ⟹ 1
1607 (kdr (kons 1 2)) ⟹ 2
1608 (let ((k (kons 1 2)))
1609 (set-kar! k 3)
1610 (kar k)) ⟹ 3
1611}}
1612
1613=== Libraries
1614
1615Libraries provide a way to organize Scheme programs into reusable parts with
1616explicitly defined interfaces to the rest of the program. This section defines
1617the notation and semantics for libraries.
1618
1619==== Library Syntax
1620
1621A library definition takes the following form:
1622
1623<macro>(define-library <library name> <library declaration> ...)</macro>
1624
1625<library name> is a list whose members are identifiers and exact non-negative
1626integers. It is used to identify the library uniquely when importing from other
1627programs or libraries. Libraries whose first identifier is scheme are reserved
1628for use by this report and future versions of this report. Libraries whose
1629first identifier is srfi are reserved for libraries implementing Scheme
1630Requests for Implementation. It is inadvisable, but not an error, for
1631identifiers in library names to contain any of the characters | \ ? * < " : > +
1632[ ] / or control characters after escapes are expanded.
1633
1634A <library declaration> is any of:
1635
1636* {{(export <export spec> ...)}}
1637
1638* {{(import <import set> ...)}}
1639
1640* {{(begin <command or definition> ...)}}
1641
1642* {{(include <filename[1]> <filename[2]> ...)}}
1643
1644* {{(include-ci <filename[1]> <filename[2]> ...)}}
1645
1646* {{(include-library-declarations <filename[1]> <filename[2]> ...)}}
1647
1648* {{(cond-expand <ce-clause[1]> <ce-clause[2]> ...}}
1649
1650An export declaration specifies a list of identifiers which can be made visible
1651to other libraries or programs. An <export spec> takes one of the following
1652forms:
1653
1654* <identifier>
1655
1656* {{(rename <identifier[1]> <identifier[2]>)}}
1657
1658In an <export spec>, an <identifier> names a single binding defined within or
1659imported into the library, where the external name for the export is the same
1660as the name of the binding within the library. A {{rename}} spec exports the
1661binding defined within or imported into the library and named by <identifier
1662[1]> in each {{(<identifier[1]> <identifier[2]>)}} pairing, using <identifier[2]>
1663as the external name.
1664
1665An import declaration provides a way to import the identifiers exported by
1666another library.
1667
1668The {{begin}}, {{include}}, and {{include}}-ci declarations are used to specify the body of
1669the library. They have the same syntax and semantics as the corresponding
1670expression types. This form of begin is analogous to, but not the same as, the
1671two types of begin defined in section 4.2.3.
1672
1673The {{include-library-declarations}} declaration is similar to {{include}} except that
1674the contents of the file are spliced directly into the current library
1675definition. This can be used, for example, to share the same export declaration
1676among multiple libraries as a simple form of library interface.
1677
1678The {{cond-expand}} declaration has the same syntax and semantics as the
1679{{cond-expand}} expression type, except that it expands to spliced-in library
1680declarations rather than expressions enclosed in begin.
1681
1682One possible implementation of libraries is as follows: After all {{cond-expand}}
1683library declarations are expanded, a new environment is constructed for the
1684library consisting of all imported bindings. The expressions from all begin,
1685{{include}} and {{include-ci}} library declarations are expanded in that environment in
1686the order in which they occur in the library. Alternatively, {{cond-expand}} and
1687{{import}} declarations may be processed in left to right order interspersed with
1688the processing of other declarations, with the environment growing as imported
1689bindings are added to it by each import declaration.
1690
1691When a library is loaded, its expressions are executed in textual order. If a
1692library’s definitions are referenced in the expanded form of a program or
1693library body, then that library must be loaded before the expanded program or
1694library body is evaluated. This rule applies transitively. If a library is
1695imported by more than one program or library, it may possibly be loaded
1696additional times.
1697
1698Similarly, during the expansion of a library (foo), if any syntax keywords
1699imported from another library (bar) are needed to expand the library, then the
1700library (bar) must be expanded and its syntax definitions evaluated before the
1701expansion of (foo).
1702
1703
1704== Standard procedures
1705
1706This chapter describes Scheme's built-in procedures. The initial (or
1707"top level") Scheme environment starts out with a number of variables
1708bound to locations containing useful values, most of which are
1709primitive procedures that manipulate data. For example, the variable
1710abs is bound to (a location initially containing) a procedure of one
1711argument that computes the absolute value of a number, and the variable
1712+ is bound to a procedure that computes sums. Built-in procedures that
1713can easily be written in terms of other built-in procedures are
1714identified as "library procedures".
1715
1716A program may use a top-level definition to bind any variable. It may
1717subsequently alter any such binding by an assignment (see
1718[[#assignments|assignments]], above). These operations do
1719not modify the behavior of Scheme's built-in procedures. Altering any
1720top-level binding that has not been introduced by a definition has an
1721unspecified effect on the behavior of the built-in procedures.
1722
1723=== Equivalence predicates
1724
1725A predicate is a procedure that always returns a boolean value (#t or #f).
1726An equivalence predicate is the computational analogue of a
1727mathematical equivalence relation (it is symmetric, reflexive, and
1728transitive). Of the equivalence predicates described in this section,
1729eq? is the finest or most discriminating, and equal? is the coarsest.
1730eqv? is slightly less discriminating than eq?.
1731
1732<procedure>(eqv? obj[1] obj[2])</procedure><br>
1733
1734The eqv? procedure defines a useful equivalence relation on objects.
1735Briefly, it returns #t if obj[1] and obj[2] should normally be regarded
1736as the same object. This relation is left slightly open to
1737interpretation, but the following partial specification of eqv? holds
1738for all implementations of Scheme.
1739
1740The eqv? procedure returns #t if:
1741
1742* obj[1] and obj[2] are both #t or both #f.
1743
1744* obj[1] and obj[2] are both symbols and
1745
1746 (string=? (symbol->string obj1)
1747 (symbol->string obj2))
1748 ===> #t
1749
1750Note: This assumes that neither obj[1] nor obj[2] is an "uninterned
1751symbol" as alluded to in the section on [[#symbols|symbols]]. This
1752report does not presume to specify the behavior of eqv? on
1753implementation-dependent extensions.
1754
1755* obj[1] and obj[2] are both numbers, are numerically equal (see =,
1756 under [[#numerical-operations|numerical operations]]), and are
1757 either both exact or both inexact.
1758
1759* obj[1] and obj[2] are both characters and are the same character
1760 according to the char=? procedure (see "[[#characters|characters]]").
1761
1762* both obj[1] and obj[2] are the empty list.
1763
1764* obj[1] and obj[2] are pairs, vectors, or strings that denote the
1765 same locations in the store.
1766
1767* obj[1] and obj[2] are procedures whose location tags are equal
1768 (see "[[#procedures|procedures]]").
1769
1770The eqv? procedure returns #f if:
1771
1772* obj[1] and obj[2] are of different types.
1773
1774* one of obj[1] and obj[2] is #t but the other is #f.
1775
1776* obj[1] and obj[2] are symbols but
1777
1778 (string=? (symbol->string obj[1])
1779 (symbol->string obj[2]))
1780 ===> #f
1781
1782* one of obj[1] and obj[2] is an exact number but the other is an
1783 inexact number.
1784
1785* obj[1] and obj[2] are numbers for which the = procedure returns #f.
1786
1787* obj[1] and obj[2] are characters for which the char=? procedure
1788 returns #f.
1789
1790* one of obj[1] and obj[2] is the empty list but the other is not.
1791
1792* obj[1] and obj[2] are pairs, vectors, or strings that denote
1793 distinct locations.
1794
1795* obj[1] and obj[2] are procedures that would behave differently
1796 (return different value(s) or have different side effects) for some
1797 arguments.
1798
1799 (eqv? 'a 'a) ===> #t
1800 (eqv? 'a 'b) ===> #f
1801 (eqv? 2 2) ===> #t
1802 (eqv? '() '()) ===> #t
1803 (eqv? 100000000 100000000) ===> #t
1804 (eqv? (cons 1 2) (cons 1 2)) ===> #f
1805 (eqv? (lambda () 1)
1806 (lambda () 2)) ===> #f
1807 (eqv? #f 'nil) ===> #f
1808 (let ((p (lambda (x) x)))
1809 (eqv? p p)) ===> #t
1810
1811The following examples illustrate cases in which the above rules do not
1812fully specify the behavior of eqv?. All that can be said about such
1813cases is that the value returned by eqv? must be a boolean.
1814
1815 (eqv? "" "") ===> unspecified
1816 (eqv? '#() '#()) ===> unspecified
1817 (eqv? (lambda (x) x)
1818 (lambda (x) x)) ===> unspecified
1819 (eqv? (lambda (x) x)
1820 (lambda (y) y)) ===> unspecified
1821
1822The next set of examples shows the use of eqv? with procedures that
1823have local state. Gen-counter must return a distinct procedure every
1824time, since each procedure has its own internal counter. Gen-loser,
1825however, returns equivalent procedures each time, since the local state
1826does not affect the value or side effects of the procedures.
1827
1828 (define gen-counter
1829 (lambda ()
1830 (let ((n 0))
1831 (lambda () (set! n (+ n 1)) n))))
1832 (let ((g (gen-counter)))
1833 (eqv? g g)) ===> #t
1834 (eqv? (gen-counter) (gen-counter))
1835 ===> #f
1836 (define gen-loser
1837 (lambda ()
1838 (let ((n 0))
1839 (lambda () (set! n (+ n 1)) 27))))
1840 (let ((g (gen-loser)))
1841 (eqv? g g)) ===> #t
1842 (eqv? (gen-loser) (gen-loser))
1843 ===> unspecified
1844
1845 (letrec ((f (lambda () (if (eqv? f g) 'both 'f)))
1846 (g (lambda () (if (eqv? f g) 'both 'g))))
1847 (eqv? f g))
1848 ===> unspecified
1849
1850 (letrec ((f (lambda () (if (eqv? f g) 'f 'both)))
1851 (g (lambda () (if (eqv? f g) 'g 'both))))
1852 (eqv? f g))
1853 ===> #f
1854
1855Since it is an error to modify constant objects (those returned by
1856literal expressions), implementations are permitted, though not
1857required, to share structure between constants where appropriate. Thus
1858the value of eqv? on constants is sometimes implementation-dependent.
1859
1860 (eqv? '(a) '(a)) ===> unspecified
1861 (eqv? "a" "a") ===> unspecified
1862 (eqv? '(b) (cdr '(a b))) ===> unspecified
1863 (let ((x '(a)))
1864 (eqv? x x)) ===> #t
1865
1866Rationale: The above definition of eqv? allows implementations
1867latitude in their treatment of procedures and literals:
1868implementations are free either to detect or to fail to detect that
1869two procedures or two literals are equivalent to each other, and
1870can decide whether or not to merge representations of equivalent
1871objects by using the same pointer or bit pattern to represent both.
1872
1873<procedure>(eq? obj[1] obj[2])</procedure><br>
1874
1875Eq? is similar to eqv? except that in some cases it is capable of
1876discerning distinctions finer than those detectable by eqv?.
1877
1878Eq? and eqv? are guaranteed to have the same behavior on symbols,
1879booleans, the empty list, pairs, procedures, and non-empty strings and
1880vectors. Eq?'s behavior on numbers and characters is
1881implementation-dependent, but it will always return either true or
1882false, and will return true only when eqv? would also return true. Eq?
1883may also behave differently from eqv? on empty vectors and empty
1884strings.
1885
1886 (eq? 'a 'a) ===> #t
1887 (eq? '(a) '(a)) ===> unspecified
1888 (eq? (list 'a) (list 'a)) ===> #f
1889 (eq? "a" "a") ===> unspecified
1890 (eq? "" "") ===> unspecified
1891 (eq? '() '()) ===> #t
1892 (eq? 2 2) ===> unspecified
1893 (eq? #\A #\A) ===> unspecified
1894 (eq? car car) ===> #t
1895 (let ((n (+ 2 3)))
1896 (eq? n n)) ===> unspecified
1897 (let ((x '(a)))
1898 (eq? x x)) ===> #t
1899 (let ((x '#()))
1900 (eq? x x)) ===> #t
1901 (let ((p (lambda (x) x)))
1902 (eq? p p)) ===> #t
1903
1904Rationale: It will usually be possible to implement eq? much more
1905efficiently than eqv?, for example, as a simple pointer comparison
1906instead of as some more complicated operation. One reason is that
1907it may not be possible to compute eqv? of two numbers in constant
1908time, whereas eq? implemented as pointer comparison will always
1909finish in constant time. Eq? may be used like eqv? in applications
1910using procedures to implement objects with state since it obeys the
1911same constraints as eqv?.
1912
1913<procedure>(equal? obj[1] obj[2])</procedure><br>
1914
1915Equal? recursively compares the contents of pairs, vectors, and
1916strings, applying eqv? on other objects such as numbers and symbols. A
1917rule of thumb is that objects are generally equal? if they print the
1918same. Equal? may fail to terminate if its arguments are circular data
1919structures.
1920
1921 (equal? 'a 'a) ===> #t
1922 (equal? '(a) '(a)) ===> #t
1923 (equal? '(a (b) c)
1924 '(a (b) c)) ===> #t
1925 (equal? "abc" "abc") ===> #t
1926 (equal? 2 2) ===> #t
1927 (equal? (make-vector 5 'a)
1928 (make-vector 5 'a)) ===> #t
1929 (equal? (lambda (x) x)
1930 (lambda (y) y)) ===> unspecified
1931
1932=== Numbers
1933
1934Numerical computation has traditionally been neglected by the Lisp
1935community. Until Common Lisp there was no carefully thought out
1936strategy for organizing numerical computation, and with the exception
1937of the MacLisp system [20] little effort was made to execute numerical
1938code efficiently. This report recognizes the excellent work of the
1939Common Lisp committee and accepts many of their recommendations. In
1940some ways this report simplifies and generalizes their proposals in a
1941manner consistent with the purposes of Scheme.
1942
1943It is important to distinguish between the mathematical numbers, the
1944Scheme numbers that attempt to model them, the machine representations
1945used to implement the Scheme numbers, and notations used to write
1946numbers. This report uses the types number, complex, real, rational,
1947and integer to refer to both mathematical numbers and Scheme numbers.
1948Machine representations such as fixed point and floating point are
1949referred to by names such as fixnum and flonum.
1950
1951==== Numerical types
1952
1953Mathematically, numbers may be arranged into a tower of subtypes in
1954which each level is a subset of the level above it:
1955
1956 number
1957 complex
1958 real
1959 rational
1960 integer
1961
1962For example, 3 is an integer. Therefore 3 is also a rational, a real,
1963and a complex. The same is true of the Scheme numbers that model 3. For
1964Scheme numbers, these types are defined by the predicates number?,
1965complex?, real?, rational?, and integer?.
1966
1967There is no simple relationship between a number's type and its
1968representation inside a computer. Although most implementations of
1969Scheme will offer at least two different representations of 3, these
1970different representations denote the same integer.
1971
1972Scheme's numerical operations treat numbers as abstract data, as
1973independent of their representation as possible. Although an
1974implementation of Scheme may use fixnum, flonum, and perhaps other
1975representations for numbers, this should not be apparent to a casual
1976programmer writing simple programs.
1977
1978It is necessary, however, to distinguish between numbers that are
1979represented exactly and those that may not be. For example, indexes
1980into data structures must be known exactly, as must some polynomial
1981coefficients in a symbolic algebra system. On the other hand, the
1982results of measurements are inherently inexact, and irrational numbers
1983may be approximated by rational and therefore inexact approximations.
1984In order to catch uses of inexact numbers where exact numbers are
1985required, Scheme explicitly distinguishes exact from inexact numbers.
1986This distinction is orthogonal to the dimension of type.
1987
1988==== Exactness
1989
1990Scheme numbers are either exact or inexact. A number is exact if it was
1991written as an exact constant or was derived from exact numbers using
1992only exact operations. A number is inexact if it was written as an
1993inexact constant, if it was derived using inexact ingredients, or if it
1994was derived using inexact operations. Thus inexactness is a contagious
1995property of a number. If two implementations produce exact results for
1996a computation that did not involve inexact intermediate results, the
1997two ultimate results will be mathematically equivalent. This is
1998generally not true of computations involving inexact numbers since
1999approximate methods such as floating point arithmetic may be used, but
2000it is the duty of each implementation to make the result as close as
2001practical to the mathematically ideal result.
2002
2003Rational operations such as + should always produce exact results when
2004given exact arguments. If the operation is unable to produce an exact
2005result, then it may either report the violation of an implementation
2006restriction or it may silently coerce its result to an inexact value.
2007See [[#implementation-restrictions|the next section]].
2008
2009With the exception of inexact->exact, the operations described in this
2010section must generally return inexact results when given any inexact
2011arguments. An operation may, however, return an exact result if it can
2012prove that the value of the result is unaffected by the inexactness of
2013its arguments. For example, multiplication of any number by an exact
2014zero may produce an exact zero result, even if the other argument is
2015inexact.
2016
2017==== Implementation restrictions
2018
2019Implementations of Scheme are not required to implement the whole
2020tower of subtypes given under "[[#Numerical types|Numerical types]]",
2021but they must implement a coherent subset consistent with both the
2022purposes of the implementation and the spirit of the Scheme
2023language. For example, an implementation in which all numbers are real
2024may still be quite useful.
2025
2026Implementations may also support only a limited range of numbers of any
2027type, subject to the requirements of this section. The supported range
2028for exact numbers of any type may be different from the supported range
2029for inexact numbers of that type. For example, an implementation that
2030uses flonums to represent all its inexact real numbers may support a
2031practically unbounded range of exact integers and rationals while
2032limiting the range of inexact reals (and therefore the range of inexact
2033integers and rationals) to the dynamic range of the flonum format.
2034Furthermore the gaps between the representable inexact integers and
2035rationals are likely to be very large in such an implementation as the
2036limits of this range are approached.
2037
2038An implementation of Scheme must support exact integers throughout the
2039range of numbers that may be used for indexes of lists, vectors, and
2040strings or that may result from computing the length of a list, vector,
2041or string. The length, vector-length, and string-length procedures must
2042return an exact integer, and it is an error to use anything but an
2043exact integer as an index. Furthermore any integer constant within the
2044index range, if expressed by an exact integer syntax, will indeed be
2045read as an exact integer, regardless of any implementation restrictions
2046that may apply outside this range. Finally, the procedures listed below
2047will always return an exact integer result provided all their arguments
2048are exact integers and the mathematically expected result is
2049representable as an exact integer within the implementation:
2050
2051 - *
2052 + abs
2053 ceiling denominator
2054 exact-integer-sqrt expt
2055 floor floor/
2056 floor-quotient floor-remainder
2057 gcd lcm
2058 max min
2059 modulo numerator
2060 quotient rationalize
2061 remainder round
2062 square truncate
2063 truncate/ truncate-quotient
2064 truncate-remainder
2065
2066CHICKEN follows the IEEE 32-bit and 64-bit floating point
2067standards on all supported platforms.
2068
2069It is the programmer’s responsibility to avoid using inexact number objects
2070with magnitude or significand too large to be represented in the
2071implementation.
2072
2073In addition, implementations may distinguish special numbers called positive
2074infinity, negative infinity, NaN, and negative zero.
2075
2076Positive infinity is regarded as an inexact real (but not rational) number that
2077represents an indeterminate value greater than the numbers represented by all
2078rational numbers. Negative infinity is regarded as an inexact real (but not
2079rational) number that represents an indeterminate value less than the numbers
2080represented by all rational numbers.
2081
2082Adding or multiplying an infinite value by any finite real value results in an
2083appropriately signed infinity; however, the sum of positive and negative
2084infinities is a NaN. Positive infinity is the reciprocal of zero, and negative
2085infinity is the reciprocal of negative zero. The behavior of the transcendental
2086functions is sensitive to infinity in accordance with IEEE 754.
2087
2088A NaN is regarded as an inexact real (but not rational) number so indeterminate
2089that it might represent any real value, including positive or negative
2090infinity, and might even be greater than positive infinity or less than
2091negative infinity. An implementation that does not support non-real numbers may
2092use NaN to represent non-real values like (sqrt -1.0) and (asin 2.0).
2093
2094A NaN always compares false to any number, including a NaN. An arithmetic
2095operation where one operand is NaN returns NaN, unless the implementation can
2096prove that the result would be the same if the NaN were replaced by any
2097rational number. Dividing zero by zero results in NaN unless both zeros are
2098exact.
2099
2100Negative zero is an inexact real value written -0.0 and is distinct (in the
2101sense of eqv?) from 0.0. A Scheme implementation is not required to distinguish
2102negative zero. If it does, however, the behavior of the transcendental
2103functions is sensitive to the distinction in accordance with IEEE 754.
2104Specifically, in a Scheme implementing both complex numbers and negative zero,
2105the branch cut of the complex logarithm function is such that (imag-part (log
2106-1.0-0.0i)) is −π rather than π.
2107
2108Furthermore, the negation of negative zero is ordinary zero and vice versa.
2109This implies that the sum of two or more negative zeros is negative, and the
2110result of subtracting (positive) zero from a negative zero is likewise
2111negative. However, numerical comparisons treat negative zero as equal to zero.
2112
2113Note that both the real and the imaginary parts of a complex number can be
2114infinities, NaNs, or negative zero.
2115
2116
2117==== Syntax of numerical constants
2118
2119For a complete formal description of the syntax of the written
2120representations for numbers, see the R7RS report. Note that case is
2121not significant in numerical constants.
2122
2123A number may be written in binary, octal, decimal, or hexadecimal by
2124the use of a radix prefix. The radix prefixes are #b (binary), #o
2125(octal), #d (decimal), and #x (hexadecimal). With no radix prefix, a
2126number is assumed to be expressed in decimal.
2127
2128A numerical constant may be specified to be either exact or inexact by
2129a prefix. The prefixes are #e for exact, and #i for inexact. An
2130exactness prefix may appear before or after any radix prefix that is
2131used. If the written representation of a number has no exactness
2132prefix, the constant may be either inexact or exact. It is inexact if
2133it contains a decimal point, an exponent, or a "#" character in the
2134place of a digit, otherwise it is exact. In systems with inexact
2135numbers of varying precisions it may be useful to specify the precision
2136of a constant. For this purpose, numerical constants may be written
2137with an exponent marker that indicates the desired precision of the
2138inexact representation. The letters s, f, d, and l specify the use of
2139short, single, double, and long precision, respectively. (When fewer
2140than four internal inexact representations exist, the four size
2141specifications are mapped onto those available. For example, an
2142implementation with two internal representations may map short and
2143single together and long and double together.) In addition, the
2144exponent marker e specifies the default precision for the
2145implementation. The default precision has at least as much precision as
2146double, but implementations may wish to allow this default to be set by
2147the user.
2148
2149 3.14159265358979F0
2150 Round to single --- 3.141593
2151 0.6L0
2152 Extend to long --- .600000000000000
2153
2154==== Numerical operations
2155
2156The numerical routines described below have argument restrictions,
2157which are encoded in the naming conventions of the arguments as
2158given in the procedure's signature. The conventions are as follows:
2159
2160; {{obj}} : any object
2161; {{list, list1, ... listj, ... list : (see "[[#pairs-and-lists|Pairs and lists]]" below)
2162; {{z, z1, ... zj, ...}} : complex number
2163; {{x, x1, ... xj, ...}} : real number
2164; {{y, y1, ... yj, ...}} : real number
2165; {{q, q1, ... qj, ...}} : rational number
2166; {{n, n1, ... nj, ...}} : integer
2167; {{k, k1, ... kj, ...}} : exact non-negative integer
2168
2169The examples used in this section assume that any
2170numerical constant written using an exact notation is indeed
2171represented as an exact number. Some examples also assume that certain
2172numerical constants written using an inexact notation can be
2173represented without loss of accuracy; the inexact constants were chosen
2174so that this is likely to be true in implementations that use flonums
2175to represent inexact numbers.
2176
2177<procedure>(number? obj)</procedure><br>
2178<procedure>(complex? obj)</procedure><br>
2179<procedure>(real? obj)</procedure><br>
2180<procedure>(rational? obj)</procedure><br>
2181<procedure>(integer? obj)</procedure><br>
2182
2183These numerical type predicates can be applied to any kind of argument,
2184including non-numbers. They return #t if the object is of the named
2185type, and otherwise they return #f. In general, if a type predicate is
2186true of a number then all higher type predicates are also true of that
2187number. Consequently, if a type predicate is false of a number, then
2188all lower type predicates are also false of that number. If z is an
2189inexact complex number, then (real? z) is true if and only if (zero?
2190(imag-part z)) is true. If x is an inexact real number, then (integer?
2191x) is true if and only if (= x (round x)).
2192
2193 (complex? 3+4i) ===> #t
2194 (complex? 3) ===> #t
2195 (real? 3) ===> #t
2196 (real? -2.5+0.0i) ===> #t
2197 (real? #e1e10) ===> #t
2198 (rational? 6/10) ===> #t
2199 (rational? 6/3) ===> #t
2200 (integer? 3+0i) ===> #t
2201 (integer? 3.0) ===> #t
2202 (integer? 8/4) ===> #t
2203
2204Note: The behavior of these type predicates on inexact numbers is
2205unreliable, since any inaccuracy may affect the result.
2206
2207Note: In many implementations the rational? procedure will be the
2208same as real?, and the complex? procedure will be the same as
2209number?, but unusual implementations may be able to represent some
2210irrational numbers exactly or may extend the number system to
2211support some kind of non-complex numbers.
2212
2213<procedure>(exact? z)</procedure><br>
2214<procedure>(inexact? z)</procedure><br>
2215
2216These numerical predicates provide tests for the exactness of a
2217quantity. For any Scheme number, precisely one of these predicates is
2218true.
2219
2220<procedure>(exact-integer? z)</procedure>
2221
2222Returns #t if z is both exact and an integer; otherwise returns #f.
2223
2224 (exact-integer? 32) ===> #t
2225 (exact-integer? 32.0) ===> #f
2226 (exact-integer? 32/5) ===> #f
2227
2228<procedure>(= z[1] z[2] z[3] ...)</procedure><br>
2229<procedure>(< x[1] x[2] x[3] ...)</procedure><br>
2230<procedure>(> x[1] x[2] x[3] ...)</procedure><br>
2231<procedure>(<= x[1] x[2] x[3] ...)</procedure><br>
2232<procedure>(>= x[1] x[2] x[3] ...)</procedure><br>
2233
2234These procedures return #t if their arguments are (respectively):
2235equal, monotonically increasing, monotonically decreasing,
2236monotonically nondecreasing, or monotonically nonincreasing.
2237
2238These predicates are required to be transitive.
2239
2240Note: The traditional implementations of these predicates in
2241Lisp-like languages are not transitive.
2242
2243Note: While it is not an error to compare inexact numbers using
2244these predicates, the results may be unreliable because a small
2245inaccuracy may affect the result; this is especially true of = and
2246zero?. When in doubt, consult a numerical analyst.
2247
2248<procedure>(zero? z)</procedure><br>
2249<procedure>(positive? x)</procedure><br>
2250<procedure>(negative? x)</procedure><br>
2251<procedure>(odd? n)</procedure><br>
2252<procedure>(even? n)</procedure><br>
2253
2254These numerical predicates test a number for a particular property,
2255returning #t or #f. See note above.
2256
2257<procedure>(max x[1] x[2] ...)</procedure><br>
2258<procedure>(min x[1] x[2] ...)</procedure><br>
2259
2260These procedures return the maximum or minimum of their arguments.
2261
2262 (max 3 4) ===> 4 ; exact
2263 (max 3.9 4) ===> 4.0 ; inexact
2264
2265Note: If any argument is inexact, then the result will also be
2266inexact (unless the procedure can prove that the inaccuracy is not
2267large enough to affect the result, which is possible only in
2268unusual implementations). If min or max is used to compare numbers
2269of mixed exactness, and the numerical value of the result cannot be
2270represented as an inexact number without loss of accuracy, then the
2271procedure may report a violation of an implementation restriction.
2272
2273<procedure>(+ z[1] ...)</procedure><br>
2274<procedure>(* z[1] ...)</procedure><br>
2275
2276These procedures return the sum or product of their arguments.
2277
2278 (+ 3 4) ===> 7
2279 (+ 3) ===> 3
2280 (+) ===> 0
2281 (* 4) ===> 4
2282 (*) ===> 1
2283
2284<procedure>(- z[1] z[2])</procedure><br>
2285<procedure>(- z)</procedure><br>
2286<procedure>(- z[1] z[2] ...)</procedure><br>
2287<procedure>(/ z[1] z[2])</procedure><br>
2288<procedure>(/ z)</procedure><br>
2289<procedure>(/ z[1] z[2] ...)</procedure><br>
2290
2291With two or more arguments, these procedures return the difference or
2292quotient of their arguments, associating to the left. With one
2293argument, however, they return the additive or multiplicative inverse
2294of their argument.
2295
2296 (- 3 4) ===> -1
2297 (- 3 4 5) ===> -6
2298 (- 3) ===> -3
2299 (/ 3 4 5) ===> 3/20
2300 (/ 3) ===> 1/3
2301
2302<procedure>(abs x)</procedure><br>
2303
2304Abs returns the absolute value of its argument.
2305
2306 (abs -7) ===> 7
2307
2308<procedure>(floor/ n[1] n[2])</procedure><br>
2309<procedure>(floor-quotient n[1] n[2])</procedure><br>
2310<procedure>(floor-remainder n[1] n[2])</procedure><br>
2311<procedure>(truncate/ n[1] n[2])</procedure><br>
2312<procedure>(truncate-quotient n[1] n[2])</procedure><br>
2313<procedure>(truncate-remainder n[1] n[2])</procedure><br>
2314
2315These procedures implement number-theoretic (integer) division. It is an error
2316if n[2] is zero. The procedures ending in / return two integers; the other
2317procedures return an integer. All the procedures compute a quotient n[q] and remainder
2318n[r] such that n[1] = n[2] * n[q] + n[r]. For each of the division operators, there are three procedures defined as
2319follows:
2320
2321 (<operator>/ n[1] n[2]) ==> n[q] n[r]
2322 (<operator>-quotient n[1] n[2]) ==> n[q]
2323 (<operator>-remainder n[1] n[2]) ==> n[r]
2324
2325The remainder n[r] is determined by the choice of integer n[q]: n[r] = n[1] − n[2] * n[q]. Each set of operators uses a different choice of n[q]:
2326
2327 floor n[q] = ⌊n[1] / n[2]⌋
2328 truncate n[q] = runcate(n[1] / n[2])
2329
2330For any of the operators, and for integers n[1] and n[2] with n[2] not equal to 0,
2331
2332 (= n[1] (+ (* n[2] (<operator>-quotient n[1] n[2]))
2333 (<operator>-remainder n[1] n[2])))
2334 ==> #t
2335
2336provided all numbers involved in that computation are exact.
2337
2338Examples:
2339
2340 (floor/ 5 2) ==> 2 1
2341 (floor/ -5 2) ==> -3 1
2342 (floor/ 5 -2) ==> -3 -1
2343 (floor/ -5 -2) ==> 2 -1
2344 (truncate/ 5 2) ==> 2 1
2345 (truncate/ -5 2) ==> -2 -1
2346 (truncate/ 5 -2) ==> -2 1
2347 (truncate/ -5 -2) ==> 2 -1
2348 (truncate/ -5.0 -2) ==> 2.0 -1.0
2349
2350<procedure>(quotient n[1] n[2])</procedure><br>
2351<procedure>(remainder n[1] n[2])</procedure><br>
2352<procedure>(modulo n[1] n[2])</procedure><br>
2353
2354These procedures implement number-theoretic (integer) division. n[2]
2355should be non-zero. All three procedures return integers. If n[1]/n[2]
2356is an integer:
2357
2358 (quotient n[1] n[2]) ===> n[1]/n[2]
2359 (remainder n[1] n[2]) ===> 0
2360 (modulo n[1] n[2]) ===> 0
2361
2362If n[1]/n[2] is not an integer:
2363
2364 (quotient n[1] n[2]) ===> n[q]
2365 (remainder n[1] n[2]) ===> n[r]
2366 (modulo n[1] n[2]) ===> n[m]
2367
2368where n[q] is n[1]/n[2] rounded towards zero, 0 < |n[r]| < |n[2]|, 0 <
2369|n[m]| < |n[2]|, n[r] and n[m] differ from n[1] by a multiple of n[2],
2370n[r] has the same sign as n[1], and n[m] has the same sign as n[2].
2371
2372From this we can conclude that for integers n[1] and n[2] with n[2] not
2373equal to 0,
2374
2375 (= n[1] (+ (* n[2] (quotient n[1] n[2]))
2376 (remainder n[1] n[2])))
2377 ===> #t
2378
2379provided all numbers involved in that computation are exact.
2380
2381 (modulo 13 4) ===> 1
2382 (remainder 13 4) ===> 1
2383
2384 (modulo -13 4) ===> 3
2385 (remainder -13 4) ===> -1
2386
2387 (modulo 13 -4) ===> -3
2388 (remainder 13 -4) ===> 1
2389
2390 (modulo -13 -4) ===> -1
2391 (remainder -13 -4) ===> -1
2392
2393 (remainder -13 -4.0) ===> -1.0 ; inexact
2394
2395<procedure>(gcd n[1] ...)</procedure><br>
2396<procedure>(lcm n[1] ...)</procedure><br>
2397
2398These procedures return the greatest common divisor or least common
2399multiple of their arguments. The result is always non-negative.
2400
2401 (gcd 32 -36) ===> 4
2402 (gcd) ===> 0
2403 (lcm 32 -36) ===> 288
2404 (lcm 32.0 -36) ===> 288.0 ; inexact
2405 (lcm) ===> 1
2406
2407<procedure>(numerator q)</procedure><br>
2408<procedure>(denominator q)</procedure><br>
2409
2410These procedures return the numerator or denominator of their argument;
2411the result is computed as if the argument was represented as a fraction
2412in lowest terms. The denominator is always positive. The denominator of
24130 is defined to be 1.
2414
2415 (numerator (/ 6 4)) ===> 3
2416 (denominator (/ 6 4)) ===> 2
2417 (denominator
2418 (exact->inexact (/ 6 4))) ===> 2.0
2419
2420<procedure>(floor x)</procedure><br>
2421<procedure>(ceiling x)</procedure><br>
2422<procedure>(truncate x)</procedure><br>
2423<procedure>(round x)</procedure><br>
2424
2425These procedures return integers. Floor returns the largest integer not
2426larger than x. Ceiling returns the smallest integer not smaller than x.
2427Truncate returns the integer closest to x whose absolute value is not
2428larger than the absolute value of x. Round returns the closest integer
2429to x, rounding to even when x is halfway between two integers.
2430
2431Rationale: Round rounds to even for consistency with the default
2432rounding mode specified by the IEEE floating point standard.
2433
2434Note: If the argument to one of these procedures is inexact, then
2435the result will also be inexact. If an exact value is needed, the
2436result should be passed to the inexact->exact procedure.
2437
2438 (floor -4.3) ===> -5.0
2439 (ceiling -4.3) ===> -4.0
2440 (truncate -4.3) ===> -4.0
2441 (round -4.3) ===> -4.0
2442
2443 (floor 3.5) ===> 3.0
2444 (ceiling 3.5) ===> 4.0
2445 (truncate 3.5) ===> 3.0
2446 (round 3.5) ===> 4.0 ; inexact
2447
2448 (round 7/2) ===> 4 ; exact
2449 (round 7) ===> 7
2450
2451<procedure>(rationalize x y)</procedure><br>
2452
2453Rationalize returns the simplest rational number differing from x by no
2454more than y. A rational number r[1] is simpler than another rational
2455number r[2] if r[1] = p[1]/q[1] and r[2] = p[2]/q[2] (in lowest terms)
2456and |p[1]| < |p[2]| and |q[1]| < |q[2]|. Thus 3/5 is simpler than 4/7.
2457Although not all rationals are comparable in this ordering (consider 2/
24587 and 3/5) any interval contains a rational number that is simpler than
2459every other rational number in that interval (the simpler 2/5 lies
2460between 2/7 and 3/5). Note that 0 = 0/1 is the simplest rational of
2461all.
2462
2463 (rationalize
2464 (inexact->exact .3) 1/10) ===> 1/3 ; exact
2465 (rationalize .3 1/10) ===> #i1/3 ; inexact
2466
2467<procedure>(exp z)</procedure><br>
2468<procedure>(log z [z2])</procedure><br>
2469<procedure>(sin z)</procedure><br>
2470<procedure>(cos z)</procedure><br>
2471<procedure>(tan z)</procedure><br>
2472<procedure>(asin z)</procedure><br>
2473<procedure>(acos z)</procedure><br>
2474<procedure>(atan z)</procedure><br>
2475<procedure>(atan y x)</procedure><br>
2476
2477These procedures are part of every implementation that supports general
2478real numbers; they compute the usual transcendental functions. The Log
2479procedure computes the natural logarithm of z (not the base ten logarithm)
2480if a single argument is given, or the base-z2 logarithm of z1 if two arguments are
2481given.
2482Asin, acos, and atan compute arcsine (sin^-1), arccosine (cos^-1), and
2483arctangent (tan^-1), respectively. The two-argument variant of atan
2484computes (angle (make-rectangular x y)) (see below), even in
2485implementations that don't support general complex numbers.
2486
2487In general, the mathematical functions log, arcsine, arccosine, and
2488arctangent are multiply defined. The value of log z is defined to be
2489the one whose imaginary part lies in the range from -pi
2490(exclusive) to pi (inclusive). log 0 is undefined. With log
2491defined this way, the values of sin^-1 z, cos^-1 z, and tan^-1 z are
2492according to the following formulae:
2493
2494 sin^-1 z = - i log (i z + (1 - z^2)^1/2)
2495
2496 cos^-1 z = pi / 2 - sin^-1 z
2497
2498 tan^-1 z = (log (1 + i z) - log (1 - i z)) / (2 i)
2499
2500The above specification follows [27], which in turn cites [19]; refer
2501to these sources for more detailed discussion of branch cuts, boundary
2502conditions, and implementation of these functions. When it is possible
2503these procedures produce a real result from a real argument.
2504
2505<procedure>(square z)</procedure>
2506
2507Returns the square of z. This is equivalent to {{(* z z)}}-
2508
2509 (square 42) ==> 1764
2510 (square 2.0) ==> 4.0
2511
2512<procedure>(exact-integer-sqrt k)</procedure>
2513
2514Returns two non-negative exact integers s and r where k = s^2 + r and k < (s + 1)^2.
2515
2516 (exact-integer-sqrt 4) ==> 2 0
2517 (exact-integer-sqrt 5) ==> 2 1
2518
2519<procedure>(expt z[1] z[2])</procedure><br>
2520
2521Returns z[1] raised to the power z[2]. For z[1] != 0
2522
2523 z[1]^z[2] = e^z[2] log z[1]
2524
25250^z is 1 if z = 0 and 0 otherwise.
2526
2527<procedure>(exact z)</procedure><br>
2528<procedure>(inexact z)</procedure><br>
2529
2530The procedure {{inexact}} returns an inexact representation of z. The value returned is the inexact number that is numerically closest to the
2531argument. For inexact arguments, the result is the same as the argument. For
2532exact complex numbers, the result is a complex number whose real and imaginary
2533parts are the result of applying inexact to the real and imaginary parts of the
2534argument, respectively. If an exact argument has no reasonably close inexact
2535equivalent (in the sense of =), then a violation of an implementation
2536restriction may be reported.
2537
2538The procedure {{exact}} returns an exact representation of z. The value returned is the exact number that is numerically closest to the
2539argument. For exact arguments, the result is the same as the argument. For
2540inexact non-integral real arguments, the implementation may return a rational
2541approximation, or may report an implementation violation. For inexact complex
2542arguments, the result is a complex number whose real and imaginary parts are
2543the result of applying exact to the real and imaginary parts of the argument,
2544respectively. If an inexact argument has no reasonably close exact equivalent,
2545(in the sense of =), then a violation of an implementation restriction may be
2546reported.
2547
2548==== Numerical input and output
2549
2550<procedure>(number->string z [radix])</procedure>
2551
2552Radix must be an exact integer. The R7RS standard only requires
2553implementations to support 2, 8, 10, or 16, but CHICKEN allows any
2554radix between 2 and 36, inclusive (note: a bug in CHICKEN 5 currently
2555limits the upper bound to 16). If omitted, radix defaults to
255610. The procedure number->string takes a number and a radix and
2557returns as a string an external representation of the given number in
2558the given radix such that
2559
2560 (let ((number number)
2561 (radix radix))
2562 (eqv? number
2563 (string->number (number->string number
2564 radix)
2565 radix)))
2566
2567is true. It is an error if no possible result makes this expression
2568true.
2569
2570If z is inexact, the radix is 10, and the above expression can be
2571satisfied by a result that contains a decimal point, then the result
2572contains a decimal point and is expressed using the minimum number of
2573digits (exclusive of exponent and trailing zeroes) needed to make the
2574above expression true [3, 5]; otherwise the format of the result is
2575unspecified.
2576
2577The result returned by number->string never contains an explicit radix
2578prefix.
2579
2580Note: The error case can occur only when z is not a complex
2581number or is a complex number with a non-rational real or imaginary
2582part.
2583
2584Rationale: If z is an inexact number represented using flonums,
2585and the radix is 10, then the above expression is normally
2586satisfied by a result containing a decimal point. The unspecified
2587case allows for infinities, NaNs, and non-flonum representations.
2588
2589As an extension to R7RS, CHICKEN supports reading and writing the
2590special IEEE floating-point numbers ''+nan'', ''+inf'' and ''-inf'',
2591as well as negative zero.
2592
2593<procedure>(string->number string)</procedure><br>
2594<procedure>(string->number string radix)</procedure><br>
2595
2596Returns a number of the maximally precise representation expressed by
2597the given string. Radix must be an exact integer. The R7RS standard
2598only requires implementations to support 2, 8, 10, or 16, but CHICKEN
2599allows any radix between 2 and 36, inclusive. If supplied, radix is a
2600default radix that may be overridden by an explicit radix prefix in
2601string (e.g. "#o177"). If radix is not supplied, then the default
2602radix is 10. If string is not a syntactically valid notation for a
2603number, then string->number returns #f.
2604
2605 (string->number "100") ===> 100
2606 (string->number "100" 16) ===> 256
2607 (string->number "1e2") ===> 100.0
2608 (string->number "15##") ===> 1500.0
2609
2610Note: The domain of string->number may be restricted by
2611implementations in the following ways. String->number is permitted
2612to return #f whenever string contains an explicit radix prefix. If
2613all numbers supported by an implementation are real, then string->
2614number is permitted to return #f whenever string uses the polar or
2615rectangular notations for complex numbers. If all numbers are
2616integers, then string->number may return #f whenever the fractional
2617notation is used. If all numbers are exact, then string->number may
2618return #f whenever an exponent marker or explicit exactness prefix
2619is used, or if a # appears in place of a digit. If all inexact
2620numbers are integers, then string->number may return #f whenever a
2621decimal point is used.
2622
2623=== Other data types
2624
2625This section describes operations on some of Scheme's non-numeric data
2626types: booleans, pairs, lists, symbols, characters, strings and
2627vectors.
2628
2629==== Booleans
2630
2631The standard boolean objects for true and false are written as #t and #f.
2632What really matters, though, are the objects that the Scheme
2633conditional expressions (if, cond, and, or, do) treat as true or false.
2634The phrase "a true value" (or sometimes just "true") means any
2635object treated as true by the conditional expressions, and the phrase
2636"a false value" (or "false") means any object treated as false by
2637the conditional expressions.
2638
2639Of all the standard Scheme values, only #f counts as false in
2640conditional expressions. Except for #f, all standard Scheme values,
2641including #t, pairs, the empty list, symbols, numbers, strings,
2642vectors, and procedures, count as true.
2643
2644Note: Programmers accustomed to other dialects of Lisp should be
2645aware that Scheme distinguishes both #f and the empty list from the
2646symbol nil.
2647
2648Boolean constants evaluate to themselves, so they do not need to be
2649quoted in programs.
2650
2651 #t ===> #t
2652 #f ===> #f
2653 '#f ===> #f
2654
2655<procedure>(not obj)</procedure><br>
2656
2657Not returns #t if obj is false, and returns #f otherwise.
2658
2659 (not #t) ===> #f
2660 (not 3) ===> #f
2661 (not (list 3)) ===> #f
2662 (not #f) ===> #t
2663 (not '()) ===> #f
2664 (not (list)) ===> #f
2665 (not 'nil) ===> #f
2666
2667<procedure>(boolean? obj)</procedure><br>
2668
2669Boolean? returns #t if obj is either #t or #f and returns #f otherwise.
2670
2671 (boolean? #f) ===> #t
2672 (boolean? 0) ===> #f
2673 (boolean? '()) ===> #f
2674
2675<procedure>(boolean=? boolean[1] boolean[2] boolean[3] ...)</procedure>
2676
2677Returns #t if all the arguments are #t or all are #f.
2678
2679==== Pairs and lists
2680
2681A pair (sometimes called a dotted pair) is a record structure with two
2682fields called the car and cdr fields (for historical reasons). Pairs
2683are created by the procedure cons. The car and cdr fields are accessed
2684by the procedures car and cdr. The car and cdr fields are assigned by
2685the procedures set-car! and set-cdr!.
2686
2687Pairs are used primarily to represent lists. A list can be defined
2688recursively as either the empty list or a pair whose cdr is a list.
2689More precisely, the set of lists is defined as the smallest set X such
2690that
2691
2692* The empty list is in X.
2693* If list is in X, then any pair whose cdr field contains list is
2694 also in X.
2695
2696The objects in the car fields of successive pairs of a list are the
2697elements of the list. For example, a two-element list is a pair whose
2698car is the first element and whose cdr is a pair whose car is the
2699second element and whose cdr is the empty list. The length of a list is
2700the number of elements, which is the same as the number of pairs.
2701
2702The empty list is a special object of its own type (it is not a pair);
2703it has no elements and its length is zero.
2704
2705Note: The above definitions imply that all lists have finite
2706length and are terminated by the empty list.
2707
2708The most general notation (external representation) for Scheme pairs is
2709the "dotted" notation (c[1] . c[2]) where c[1] is the value of the
2710car field and c[2] is the value of the cdr field. For example (4 . 5)
2711is a pair whose car is 4 and whose cdr is 5. Note that (4 . 5) is the
2712external representation of a pair, not an expression that evaluates to
2713a pair.
2714
2715A more streamlined notation can be used for lists: the elements of the
2716list are simply enclosed in parentheses and separated by spaces. The
2717empty list is written () . For example,
2718
2719 (a b c d e)
2720
2721and
2722
2723 (a . (b . (c . (d . (e . ())))))
2724
2725are equivalent notations for a list of symbols.
2726
2727A chain of pairs not ending in the empty list is called an improper
2728list. Note that an improper list is not a list. The list and dotted
2729notations can be combined to represent improper lists:
2730
2731 (a b c . d)
2732
2733is equivalent to
2734
2735 (a . (b . (c . d)))
2736
2737Whether a given pair is a list depends upon what is stored in the cdr
2738field. When the set-cdr! procedure is used, an object can be a list one
2739moment and not the next:
2740
2741 (define x (list 'a 'b 'c))
2742 (define y x)
2743 y ===> (a b c)
2744 (list? y) ===> #t
2745 (set-cdr! x 4) ===> unspecified
2746 x ===> (a . 4)
2747 (eqv? x y) ===> #t
2748 y ===> (a . 4)
2749 (list? y) ===> #f
2750 (set-cdr! x x) ===> unspecified
2751 (list? x) ===> #f
2752
2753Within literal expressions and representations of objects read by the
2754read procedure, the forms '<datum>, `<datum>, ,<datum>, and ,@<datum>
2755denote two-element lists whose first elements are the symbols quote,
2756quasiquote, unquote, and unquote-splicing, respectively. The second
2757element in each case is <datum>. This convention is supported so that
2758arbitrary Scheme programs may be represented as lists. That is,
2759according to Scheme's grammar, every <expression> is also a <datum>.
2760Among other things, this permits the use of the read procedure to
2761parse Scheme programs.
2762
2763<procedure>(pair? obj)</procedure><br>
2764
2765Pair? returns #t if obj is a pair, and otherwise returns #f.
2766
2767 (pair? '(a . b)) ===> #t
2768 (pair? '(a b c)) ===> #t
2769 (pair? '()) ===> #f
2770 (pair? '#(a b)) ===> #f
2771
2772<procedure>(cons obj[1] obj[2])</procedure><br>
2773
2774Returns a newly allocated pair whose car is obj[1] and whose cdr is
2775obj[2]. The pair is guaranteed to be different (in the sense of eqv?)
2776from every existing object.
2777
2778 (cons 'a '()) ===> (a)
2779 (cons '(a) '(b c d)) ===> ((a) b c d)
2780 (cons "a" '(b c)) ===> ("a" b c)
2781 (cons 'a 3) ===> (a . 3)
2782 (cons '(a b) 'c) ===> ((a b) . c)
2783
2784<procedure>(car pair)</procedure><br>
2785
2786Returns the contents of the car field of pair. Note that it is an error
2787to take the car of the empty list.
2788
2789 (car '(a b c)) ===> a
2790 (car '((a) b c d)) ===> (a)
2791 (car '(1 . 2)) ===> 1
2792 (car '()) ===> error
2793
2794<procedure>(cdr pair)</procedure><br>
2795
2796Returns the contents of the cdr field of pair. Note that it is an error
2797to take the cdr of the empty list.
2798
2799 (cdr '((a) b c d)) ===> (b c d)
2800 (cdr '(1 . 2)) ===> 2
2801 (cdr '()) ===> error
2802
2803<procedure>(set-car! pair obj)</procedure><br>
2804
2805Stores obj in the car field of pair. The value returned by set-car! is
2806unspecified.
2807
2808 (define (f) (list 'not-a-constant-list))
2809 (define (g) '(constant-list))
2810 (set-car! (f) 3) ===> unspecified
2811 (set-car! (g) 3) ===> error
2812
2813<procedure>(set-cdr! pair obj)</procedure><br>
2814
2815Stores obj in the cdr field of pair. The value returned by set-cdr! is
2816unspecified.
2817
2818<procedure>(null? obj)</procedure><br>
2819
2820Returns #t if obj is the empty list, otherwise returns #f.
2821
2822<procedure>(list? obj)</procedure><br>
2823
2824Returns #t if obj is a list, otherwise returns #f. By definition, all
2825lists have finite length and are terminated by the empty list.
2826
2827 (list? '(a b c)) ===> #t
2828 (list? '()) ===> #t
2829 (list? '(a . b)) ===> #f
2830 (let ((x (list 'a)))
2831 (set-cdr! x x)
2832 (list? x)) ===> #f
2833
2834<procedure>(make-list k [fill]}</procedure>
2835
2836Returns a newly allocated list of k elements. If a second argument is given, then each element is initialized to {{fill}}. Otherwise the initial contents of each element is unspecified.
2837
2838 (make-list 2 3) ==> (3 3)
2839
2840<procedure>(list obj ...)</procedure><br>
2841
2842Returns a newly allocated list of its arguments.
2843
2844 (list 'a (+ 3 4) 'c) ===> (a 7 c)
2845 (list) ===> ()
2846
2847<procedure>(length list)</procedure><br>
2848
2849Returns the length of list.
2850
2851 (length '(a b c)) ===> 3
2852 (length '(a (b) (c d e))) ===> 3
2853 (length '()) ===> 0
2854
2855<procedure>(append list ...)</procedure><br>
2856
2857Returns a list consisting of the elements of the first list followed by
2858the elements of the other lists.
2859
2860 (append '(x) '(y)) ===> (x y)
2861 (append '(a) '(b c d)) ===> (a b c d)
2862 (append '(a (b)) '((c))) ===> (a (b) (c))
2863
2864The resulting list is always newly allocated, except that it shares
2865structure with the last list argument. The last argument may actually
2866be any object; an improper list results if the last argument is not a
2867proper list.
2868
2869 (append '(a b) '(c . d)) ===> (a b c . d)
2870 (append '() 'a) ===> a
2871
2872<procedure>(reverse list)</procedure><br>
2873
2874Returns a newly allocated list consisting of the elements of list in
2875reverse order.
2876
2877 (reverse '(a b c)) ===> (c b a)
2878 (reverse '(a (b c) d (e (f))))
2879 ===> ((e (f)) d (b c) a)
2880
2881<procedure>(list-tail list k)</procedure><br>
2882
2883Returns the sublist of list obtained by omitting the first k elements.
2884It is an error if list has fewer than k elements. List-tail could be
2885defined by
2886
2887 (define list-tail
2888 (lambda (x k)
2889 (if (zero? k)
2890 x
2891 (list-tail (cdr x) (- k 1)))))
2892
2893<procedure>(list-ref list k)</procedure><br>
2894
2895Returns the kth element of list. (This is the same as the car of
2896(list-tail list k).) It is an error if list has fewer than k elements.
2897
2898 (list-ref '(a b c d) 2) ===> c
2899 (list-ref '(a b c d)
2900 (inexact->exact (round 1.8)))
2901 ===> c
2902
2903<procedure>(list-set! list k obj)</procedure>
2904
2905It is an error if k is not a valid index of list.
2906
2907The {{list-set!}} procedure stores obj in element k of list.
2908
2909 (let ((ls (list 'one 'two 'five!)))
2910 (list-set! ls 2 'three)
2911 ls)
2912 ==> (one two three)
2913
2914 (list-set! '(0 1 2) 1 "oops")
2915 ==> error ; constant list
2916
2917<procedure>(memq obj list)</procedure><br>
2918<procedure>(memv obj list)</procedure><br>
2919<procedure>(member obj list [compare])</procedure><br>
2920
2921These procedures return the first sublist of list whose car is obj,
2922where the sublists of list are the non-empty lists returned by
2923{{(list-tail list k)}} for k less than the length of list. If obj does not
2924occur in list, then #f (not the empty list) is returned. {{memq}} uses {{eq?}}
2925to compare obj with the elements of list, while {{memv}} uses {{eqv?}} and
2926member {{compare}} if given, and {{equal?}} otherwise.
2927
2928 (memq 'a '(a b c)) ===> (a b c)
2929 (memq 'b '(a b c)) ===> (b c)
2930 (memq 'a '(b c d)) ===> #f
2931 (memq (list 'a) '(b (a) c)) ===> #f
2932 (member (list 'a)
2933 '(b (a) c)) ===> ((a) c)
2934 (memq 101 '(100 101 102)) ===> unspecified
2935 (memv 101 '(100 101 102)) ===> (101 102)
2936
2937<procedure>(assq obj alist)</procedure><br>
2938<procedure>(assv obj alist)</procedure><br>
2939<procedure>(assoc obj alist [compare])</procedure><br>
2940
2941Alist (for "association list") must be a list of pairs. These
2942procedures find the first pair in alist whose car field is obj, and
2943returns that pair. If no pair in alist has obj as its car, then #f (not
2944the empty list) is returned. {{assq}} uses {{eq?}} to compare obj with the car
2945fields of the pairs in alist, while {{assv}} uses {{eqv?}} and {{assoc}} uses
2946{{compare}}, if given, otherwise {{equal?}}.
2947
2948 (define e '((a 1) (b 2) (c 3)))
2949 (assq 'a e) ===> (a 1)
2950 (assq 'b e) ===> (b 2)
2951 (assq 'd e) ===> #f
2952 (assq (list 'a) '(((a)) ((b)) ((c))))
2953 ===> #f
2954 (assoc (list 'a) '(((a)) ((b)) ((c))))
2955 ===> ((a))
2956 (assq 5 '((2 3) (5 7) (11 13)))
2957 ===> unspecified
2958 (assv 5 '((2 3) (5 7) (11 13)))
2959 ===> (5 7)
2960
2961Rationale: Although they are ordinarily used as predicates, memq,
2962memv, member, assq, assv, and assoc do not have question marks in
2963their names because they return useful values rather than just #t
2964or #f.
2965
2966<procedure>(list-copy obj)</procedure>
2967
2968Returns a newly allocated copy of the given obj if it is a list. Only the pairs themselves are copied; the cars of the result are the same (in the sense of {{eqv?}}) as the cars of list. If obj is an improper list, so is the result, and the final cdrs are the same in
2969the sense of {{eqv?}}. An obj which is not a list is returned unchanged. It is an error if
2970obj is a circular list.
2971
2972 (define a '(1 8 2 8)) ; a may be immutable
2973 (define b (list-copy a))
2974 (set-car! b 3) ; b is mutable
2975 b ==> (3 8 2 8)
2976 a ==> (1 8 2 8)
2977
2978==== Symbols
2979
2980Symbols are objects whose usefulness rests on the fact that two symbols
2981are identical (in the sense of eqv?) if and only if their names are
2982spelled the same way. This is exactly the property needed to represent
2983identifiers in programs, and so most implementations of Scheme use them
2984internally for that purpose. Symbols are useful for many other
2985applications; for instance, they may be used the way enumerated values
2986are used in Pascal.
2987
2988The rules for writing a symbol are exactly the same as the rules for
2989writing an identifier.
2990
2991It is guaranteed that any symbol that has been returned as part of a
2992literal expression, or read using the read procedure, and subsequently
2993written out using the write procedure, will read back in as the
2994identical symbol (in the sense of eqv?). The string->symbol procedure,
2995however, can create symbols for which this write/read invariance may
2996not hold because their names contain special characters or letters in
2997the non-standard case.
2998
2999Note: Some implementations of Scheme have a feature known as
3000"slashification" in order to guarantee write/read invariance for
3001all symbols, but historically the most important use of this
3002feature has been to compensate for the lack of a string data type.
3003
3004Some implementations also have "uninterned symbols", which defeat
3005write/read invariance even in implementations with slashification,
3006and also generate exceptions to the rule that two symbols are the
3007same if and only if their names are spelled the same.
3008
3009<procedure>(symbol? obj)</procedure><br>
3010
3011Returns #t if obj is a symbol, otherwise returns #f.
3012
3013 (symbol? 'foo) ===> #t
3014 (symbol? (car '(a b))) ===> #t
3015 (symbol? "bar") ===> #f
3016 (symbol? 'nil) ===> #t
3017 (symbol? '()) ===> #f
3018 (symbol? #f) ===> #f
3019
3020<procedure>(symbol=? symbol[1] symbol[2] symbol[3] ...)</procedure>
3021
3022Returns #t if all the arguments all have the same names in the sense of {{string=?}}.
3023
3024Note: The definition above assumes that none of the arguments are uninterned symbols.
3025
3026<procedure>(symbol->string symbol)</procedure><br>
3027
3028Returns the name of symbol as a string. If the symbol was part of an
3029object returned as the value of a literal expression (see
3030"[[#literal-expressions|literal expressions]]") or by a call to the
3031read procedure, and its name contains alphabetic characters, then the
3032string returned will contain characters in the implementation's
3033preferred standard case -- some implementations will prefer upper
3034case, others lower case. If the symbol was returned by string->symbol,
3035the case of characters in the string returned will be the same as the
3036case in the string that was passed to string->symbol. It is an error
3037to apply mutation procedures like string-set! to strings returned by
3038this procedure.
3039
3040The following examples assume that the implementation's standard case
3041is lower case:
3042
3043 (symbol->string 'flying-fish)
3044 ===> "flying-fish"
3045 (symbol->string 'Martin) ===> "martin"
3046 (symbol->string
3047 (string->symbol "Malvina"))
3048 ===> "Malvina"
3049
3050<procedure>(string->symbol string)</procedure><br>
3051
3052Returns the symbol whose name is string. This procedure can create
3053symbols with names containing special characters or letters in the
3054non-standard case, but it is usually a bad idea to create such symbols
3055because in some implementations of Scheme they cannot be read as
3056themselves. See symbol->string.
3057
3058The following examples assume that the implementation's standard case
3059is lower case:
3060
3061 (eq? 'mISSISSIppi 'mississippi)
3062 ===> #t
3063 (string->symbol "mISSISSIppi")
3064 ===> the symbol with name "mISSISSIppi"
3065 (eq? 'bitBlt (string->symbol "bitBlt"))
3066 ===> #f
3067 (eq? 'JollyWog
3068 (string->symbol
3069 (symbol->string 'JollyWog)))
3070 ===> #t
3071 (string=? "K. Harper, M.D."
3072 (symbol->string
3073 (string->symbol "K. Harper, M.D.")))
3074 ===> #t
3075
3076==== Characters
3077
3078Characters are objects that represent printed characters such as
3079letters and digits. Characters are written using the notation #\
3080<character> or #\<character name>. For example:
3081
3082Characters are written using the notation {{#\<character>}} or {{#\<character name>}}
3083or {{#\x<hex scalar value>}}.
3084
3085The following character names must be supported by all implementations with the
3086given values. Implementations may add other names provided they cannot be
3087interpreted as hex scalar values preceded by x.
3088
3089 #\alarm ; U+0007
3090 #\backspace ; U+0008
3091 #\delete ; U+007F
3092 #\escape ; U+001B
3093 #\newline ; the linefeed character, U+000A
3094 #\null ; the null character, U+0000
3095 #\return ; the return character, U+000D
3096 #\space ; the preferred way to write a space
3097 #\tab ; the tab character, U+0009
3098
3099Here are some additional examples:
3100
3101 #\a ; lower case letter
3102 #\A ; upper case letter
3103 #\( ; left parenthesis
3104 #\ ; the space character
3105 #\space ; the preferred way to write a space
3106 #\newline ; the newline character
3107
3108Case is significant in #\<character>, but not in #\<character name>. If
3109<character> in #\<character> is alphabetic, then the character
3110following <character> must be a delimiter character such as a space or
3111parenthesis. This rule resolves the ambiguous case where, for example,
3112the sequence of characters "#\space" could be taken to be either a
3113representation of the space character or a representation of the
3114character "#\s" followed by a representation of the symbol "pace."
3115
3116Characters written in the #\ notation are self-evaluating. That is,
3117they do not have to be quoted in programs. Some of the procedures that
3118operate on characters ignore the difference between upper case and
3119lower case. The procedures that ignore case have "-ci" (for "case
3120insensitive") embedded in their names.
3121
3122<procedure>(char? obj)</procedure><br>
3123
3124Returns #t if obj is a character, otherwise returns #f.
3125
3126<procedure>(char=? char[1] char[2] char[3] ...)</procedure><br>
3127<procedure>(char<? char[1] char[2] char[3] ...)</procedure><br>
3128<procedure>(char>? char[1] char[2] char[3] ...)</procedure><br>
3129<procedure>(char<=? char[1] char[2] char[3] ...)</procedure><br>
3130<procedure>(char>=? char[1] char[2] char[3] ...)</procedure><br>
3131
3132These procedures impose a total ordering on the set of characters. It
3133is guaranteed that under this ordering:
3134
3135* The upper case characters are in order. For example, (char<? #\A #\
3136 B) returns #t.
3137* The lower case characters are in order. For example, (char<? #\a #\
3138 b) returns #t.
3139* The digits are in order. For example, (char<? #\0 #\9) returns #t.
3140* Either all the digits precede all the upper case letters, or vice
3141 versa.
3142* Either all the digits precede all the lower case letters, or vice
3143 versa.
3144
3145Some implementations may generalize these procedures to take more than
3146two arguments, as with the corresponding numerical predicates.
3147
3148<procedure>(char-ci=? char[1] char[2] char[3] ...)</procedure><br>
3149<procedure>(char-ci<? char[1] char[2] char[3] ...)</procedure><br>
3150<procedure>(char-ci>? char[1] char[2] char[3] ...)</procedure><br>
3151<procedure>(char-ci<=? char[1] char[2] char[3] ...)</procedure><br>
3152<procedure>(char-ci>=? char[1] char[2] char[3] ...)</procedure><br>
3153
3154These procedures are similar to char=? et cetera, but they treat upper
3155case and lower case letters as the same. For example, (char-ci=? #\A #\
3156a) returns #t. Some implementations may generalize these procedures to
3157take more than two arguments, as with the corresponding numerical
3158predicates.
3159
3160<procedure>(char-alphabetic? char)</procedure><br>
3161<procedure>(char-numeric? char)</procedure><br>
3162<procedure>(char-whitespace? char)</procedure><br>
3163<procedure>(char-upper-case? letter)</procedure><br>
3164<procedure>(char-lower-case? letter)</procedure><br>
3165
3166These procedures return #t if their arguments are alphabetic, numeric,
3167whitespace, upper case, or lower case characters, respectively,
3168otherwise they return #f. The following remarks, which are specific to
3169the ASCII character set, are intended only as a guide: The alphabetic
3170characters are the 52 upper and lower case letters. The numeric
3171characters are the ten decimal digits. The whitespace characters are
3172space, tab, line feed, form feed, and carriage return.
3173
3174<procedure>(char->integer char)</procedure><br>
3175<procedure>(integer->char n)</procedure><br>
3176
3177Given a character, char->integer returns an exact integer
3178representation of the character. Given an exact integer that is the
3179image of a character under char->integer, integer->char returns that
3180character. These procedures implement order-preserving isomorphisms
3181between the set of characters under the char<=? ordering and some
3182subset of the integers under the <= ordering. That is, if
3183
3184 (char<=? a b) ===> #t and (<= x y) ===> #t
3185
3186and x and y are in the domain of integer->char, then
3187
3188 (<= (char->integer a)
3189 (char->integer b)) ===> #t
3190
3191 (char<=? (integer->char x)
3192 (integer->char y)) ===> #t
3193
3194Note that {{integer->char}} does currently not detect
3195a negative argument and will quietly convert {{-1}} to
3196{{#x1ffff}} in CHICKEN.
3197
3198==== Strings
3199
3200Strings are sequences of characters. Strings are written as sequences of
3201characters enclosed within quotation marks ("). Within a string literal,
3202various escape sequences represent characters other than themselves. Escape
3203sequences always start with a backslash (\):
3204
3205* \a : alarm, U+0007
3206
3207* \b : backspace, U+0008
3208
3209* \t : character tabulation, U+0009
3210
3211* \n : linefeed, U+000A
3212
3213* \r : return, U+000D
3214
3215* \" : double quote, U+0022
3216
3217* \\ : backslash, U+005C
3218
3219* \| : vertical line, U+007C
3220
3221* \<intraline whitespace>*<line ending> <intraline whitespace>* : nothing
3222
3223* \x<hex scalar value>; : specified character (note the terminating
3224 semi-colon).
3225
3226The result is unspecified if any other character in a string occurs after a
3227backslash.
3228
3229Except for a line ending, any character outside of an escape sequence stands
3230for itself in the string literal. A line ending which is preceded by \
3231<intraline whitespace> expands to nothing (along with any trailing intraline
3232whitespace), and can be used to indent strings for improved legibility. Any
3233other line ending has the same effect as inserting a \n character into the
3234string.
3235
3236Examples:
3237
3238 "The word \"recursion\" has many meanings."
3239 "Another example:\ntwo lines of text"
3240 "Here's text \
3241 containing just one line"
3242 "\x03B1; is named GREEK SMALL LETTER ALPHA."
3243
3244The length of a string is the
3245number of characters that it contains. This number is an exact, non-negative
3246integer that is fixed when the string is created. The valid indexes of a string
3247are the exact non-negative integers less than the length of the string. The
3248first character of a string has index 0, the second has index 1, and so on.
3249
3250<procedure>(string? obj)</procedure><br>
3251
3252Returns #t if obj is a string, otherwise returns #f.
3253
3254<procedure>(make-string k)</procedure><br>
3255<procedure>(make-string k char)</procedure><br>
3256
3257Make-string returns a newly allocated string of length k. If char is
3258given, then all elements of the string are initialized to char,
3259otherwise the contents of the string are unspecified.
3260
3261<procedure>(string char ...)</procedure><br>
3262
3263Returns a newly allocated string composed of the arguments.
3264
3265<procedure>(string-length string)</procedure><br>
3266
3267Returns the number of characters in the given string.
3268
3269<procedure>(string-ref string k)</procedure><br>
3270
3271k must be a valid index of string. String-ref returns character k of
3272string using zero-origin indexing.
3273
3274<procedure>(string-set! string k char)</procedure><br>
3275
3276k must be a valid index of string. String-set! stores char in element k
3277of string and returns an unspecified value.
3278
3279 (define (f) (make-string 3 #\*))
3280 (define (g) "***")
3281 (string-set! (f) 0 #\?) ===> unspecified
3282 (string-set! (g) 0 #\?) ===> error
3283 (string-set! (symbol->string 'immutable)
3284 0
3285 #\?) ===> error
3286
3287<procedure>(string=? string[1] string[2] string[3] ...)</procedure><br>
3288
3289Returns #t if the two strings are the same length and contain the same
3290characters in the same positions, otherwise returns #f.
3291
3292<procedure>(string<? string[1] string[2] string[3] ...)</procedure><br>
3293<procedure>(string>? string[1] string[2] string[3] ...)</procedure><br>
3294<procedure>(string<=? string[1] string[2] string[3] ...)</procedure><br>
3295<procedure>(string>=? string[1] string[2] string[3] ...)</procedure><br>
3296
3297These procedures are the lexicographic extensions to strings of the
3298corresponding orderings on characters. For example, string<? is the
3299lexicographic ordering on strings induced by the ordering char<? on
3300characters. If two strings differ in length but are the same up to the
3301length of the shorter string, the shorter string is considered to be
3302lexicographically less than the longer string.
3303
3304<procedure>(substring string start [end])</procedure><br>
3305
3306String must be a string, and start and end must be exact integers
3307satisfying
3308
3309 0 <= start <= end <= (string-length string)
3310
3311Substring returns a newly allocated string formed from the characters
3312of string beginning with index start (inclusive) and ending with index
3313end (exclusive). The {{end}} argument is optional and defaults to the
3314length of the string, this is a non-standard extension in CHICKEN.
3315
3316<procedure>(string-append string ...)</procedure><br>
3317
3318Returns a newly allocated string whose characters form the
3319concatenation of the given strings.
3320
3321<procedure>(string->list string [start [end]])</procedure><br>
3322<procedure>(list->string list)</procedure><br>
3323
3324String->list returns a newly allocated list of the characters that make
3325up the given string between start and end. List->string returns a newly allocated string
3326formed from the characters in the list list, which must be a list of
3327characters. String->list and list->string are inverses so far as equal?
3328is concerned.
3329
3330<procedure>(string-copy string [start [end]])</procedure><br>
3331
3332Returns a newly allocated copy of the given string.
3333
3334<procedure>(string-copy! to at from [start [end]])</procedure>
3335
3336It is an error if at is less than zero or greater than the length of to. It is also an error if {{(- (string-length to) at)}} is less than {{(- end start)}}.
3337
3338Copies the characters of string from between start and end to string to, starting at
3339at. The order in which characters are copied is unspecified, except that if the
3340source and destination overlap, copying takes place as if the source is first
3341copied into a temporary string and then into the destination. This can be
3342achieved without allocating storage by making sure to copy in the correct
3343direction in such circumstances.
3344
3345 (define a "12345")
3346 (define b (string-copy "abcde"))
3347 (string-copy! b 1 a 0 2)
3348 b ==> "a12de"
3349
3350<procedure>(string-fill! string char +#!optional start end)</procedure><br>
3351
3352Stores char in every element of the given string and returns an
3353unspecified value. The optional start and end arguments specify
3354the part of the string to be filled and default to the complete string.
3355
3356==== Vectors
3357
3358Vectors are heterogenous structures whose elements are indexed by
3359integers. A vector typically occupies less space than a list of the
3360same length, and the average time required to access a randomly chosen
3361element is typically less for the vector than for the list.
3362
3363The length of a vector is the number of elements that it contains. This
3364number is a non-negative integer that is fixed when the vector is
3365created. The valid indexes of a vector are the exact non-negative
3366integers less than the length of the vector. The first element in a
3367vector is indexed by zero, and the last element is indexed by one less
3368than the length of the vector.
3369
3370Vectors are written using the notation #(obj ...). For example, a
3371vector of length 3 containing the number zero in element 0, the list (2
33722 2 2) in element 1, and the string "Anna" in element 2 can be written
3373as following:
3374
3375 #(0 (2 2 2 2) "Anna")
3376
3377Vector constants are self-evaluating, so they do not need
3378to be quoted in programs.
3379
3380<procedure>(vector? obj)</procedure><br>
3381
3382Returns #t if obj is a vector, otherwise returns #f.
3383
3384<procedure>(make-vector k)</procedure><br>
3385<procedure>(make-vector k fill)</procedure><br>
3386
3387Returns a newly allocated vector of k elements. If a second argument is
3388given, then each element is initialized to fill. Otherwise the initial
3389contents of each element is unspecified.
3390
3391<procedure>(vector obj ...)</procedure><br>
3392
3393Returns a newly allocated vector whose elements contain the given
3394arguments. Analogous to list.
3395
3396 (vector 'a 'b 'c) ===> #(a b c)
3397
3398<procedure>(vector-length vector)</procedure><br>
3399
3400Returns the number of elements in vector as an exact integer.
3401
3402<procedure>(vector-ref vector k)</procedure><br>
3403
3404k must be a valid index of vector. Vector-ref returns the contents of
3405element k of vector.
3406
3407 (vector-ref '#(1 1 2 3 5 8 13 21)
3408 5)
3409 ===> 8
3410 (vector-ref '#(1 1 2 3 5 8 13 21)
3411 (let ((i (round (* 2 (acos -1)))))
3412 (if (inexact? i)
3413 (inexact->exact i)
3414 i)))
3415 ===> 13
3416
3417<procedure>(vector-set! vector k obj)</procedure><br>
3418
3419k must be a valid index of vector. Vector-set! stores obj in element k
3420of vector. The value returned by vector-set! is unspecified.
3421
3422 (let ((vec (vector 0 '(2 2 2 2) "Anna")))
3423 (vector-set! vec 1 '("Sue" "Sue"))
3424 vec)
3425 ===> #(0 ("Sue" "Sue") "Anna")
3426
3427 (vector-set! '#(0 1 2) 1 "doe")
3428 ===> error ; constant vector
3429
3430<procedure>(vector->list vector [start [end]])</procedure><br>
3431<procedure>(list->vector list)</procedure><br>
3432
3433Vector->list returns a newly allocated list of the objects contained in
3434the elements of vector. List->vector returns a newly created vector
3435initialized to the elements of the list list.
3436
3437 (vector->list '#(dah dah didah))
3438 ===> (dah dah didah)
3439 (list->vector '(dididit dah))
3440 ===> #(dididit dah)
3441
3442<procedure>(vector-fill! vector fill)</procedure><br>
3443
3444Stores fill in every element of vector. The value returned by
3445vector-fill! is unspecified.
3446
3447<procedure>(vector->string vector [start [end]])</procedure><br>
3448<procedure(string->vector string [start [end]])</procedure>
3449
3450It is an error if any element of vector between start and end is not a character.
3451
3452The vector->string procedure returns a newly allocated string of the objects
3453contained in the elements of vector between start and end. The string->vector procedure returns a newly created vector initialized to
3454the elements of the string string between start and end.
3455
3456In both procedures, order is preserved.
3457
3458 (string->vector "ABC") ==> #(#\A #\B #\C)
3459 (vector->string #(#\1 #\2 #\3) ==> "123"
3460
3461<procedure>(vector-copy vector [start [end]])</procedure>
3462
3463Returns a newly allocated copy of the elements of the given vector between
3464start and end. The elements of the new vector are the same (in the sense of eqv?) as the
3465elements of the old.
3466
3467 (define a #(1 8 2 8)) ; a may be immutable
3468 (define b (vector-copy a))
3469 (vector-set! b 0 3) ; b is mutable
3470 b ==> #(3 8 2 8)
3471 (define c (vector-copy b 1 3))
3472 c ==> #(8 2)
3473
3474<procedure>(vector-copy! to at from [start [end]])</procedure>
3475
3476It is an error if at is less than zero or greater than the length of to. It is also an error if {{(- (vector-length to) at)}} is less than {{(- end start)}}.
3477
3478Copies the elements of vector from between start and end to vector to, starting at
3479at. The order in which elements are copied is unspecified, except that if the
3480source and destination overlap, copying takes place as if the source is first
3481copied into a temporary vector and then into the destination. This can be
3482achieved without allocating storage by making sure to copy in the correct
3483direction in such circumstances.
3484
3485 (define a (vector 1 2 3 4 5))
3486 (define b (vector 10 20 30 40 50))
3487 (vector-copy! b 1 a 0 2)
3488 b ==> #(10 1 2 40 50)
3489
3490<procedure>(vector-append vector ....)</procedure>
3491
3492Returns a newly allocated vector whose elements are the concatenation of the
3493elements of the given vectors.
3494
3495 (vector-append #(a b c) #(d e f)) ==> #(a b c d e f)
3496
3497<procedure>(vector-fill! vector fill [start [end)]])</procedure>
3498
3499The vector-fill! procedure stores fill in the elements of vector between start and
3500end.
3501
3502 (define a (vector 1 2 3 4 5))
3503 (vector-fill! a 'smash 2 4)
3504 a ==>#(1 2 smash smash 5)
3505
3506==== Bytevectors
3507
3508Bytevectors represent blocks of binary data. They are fixed-length sequences of
3509bytes, where a byte is an exact integer in the range from 0 to 255 inclusive. A
3510bytevector is typically more space-efficient than a vector containing the same
3511values.
3512
3513See [[Module (chicken bytevector)|The (chicken bytevector) module]] for more
3514information. {{(scheme base)}} re-exports all R7RS-specific procedures from
3515that module.
3516
3517=== Control features
3518
3519This chapter describes various primitive procedures which control the
3520flow of program execution in special ways. The procedure? predicate is
3521also described here.
3522
3523<procedure>(procedure? obj)</procedure><br>
3524
3525Returns #t if obj is a procedure, otherwise returns #f.
3526
3527 (procedure? car) ===> #t
3528 (procedure? 'car) ===> #f
3529 (procedure? (lambda (x) (* x x)))
3530 ===> #t
3531 (procedure? '(lambda (x) (* x x)))
3532 ===> #f
3533 (call-with-current-continuation procedure?)
3534 ===> #t
3535
3536<procedure>(apply proc arg[1] ... args)</procedure><br>
3537
3538Proc must be a procedure and args must be a list. Calls proc with the
3539elements of the list (append (list arg[1] ...) args) as the actual
3540arguments.
3541
3542 (apply + (list 3 4)) ===> 7
3543
3544 (define compose
3545 (lambda (f g)
3546 (lambda args
3547 (f (apply g args)))))
3548
3549 ((compose sqrt *) 12 75) ===> 30
3550
3551<procedure>(map proc list[1] list[2] ...)</procedure><br>
3552
3553The lists must be lists, and proc must be a procedure taking as many
3554arguments as there are lists and returning a single value. Map applies
3555proc element-wise to the elements of the lists and returns a list of
3556the results, in order. The dynamic order in which proc is applied to
3557the elements of the lists is unspecified.
3558
3559Like in SRFI-1, this procedure allows the arguments to be of unequal
3560length; it terminates when the shortest list runs out. This is a
3561CHICKEN extension to R7RS.
3562
3563 (map cadr '((a b) (d e) (g h)))
3564 ===> (b e h)
3565
3566 (map (lambda (n) (expt n n))
3567 '(1 2 3 4 5))
3568 ===> (1 4 27 256 3125)
3569
3570 (map + '(1 2 3) '(4 5 6)) ===> (5 7 9)
3571
3572 (let ((count 0))
3573 (map (lambda (ignored)
3574 (set! count (+ count 1))
3575 count)
3576 '(a b))) ===> (1 2) or (2 1)
3577
3578<procedure>(string-map proc string[1] string[2] ...)</procedure>
3579
3580It is an error if proc does not accept as many arguments as there are strings and return a single character.
3581
3582The string-map procedure applies proc element-wise to the elements of the
3583strings and returns a string of the results, in order. If more than one
3584string is given and not all strings have the same length, string-map terminates
3585when the shortest string runs out. The dynamic order in which
3586proc is applied to the elements of the
3587strings is unspecified. If multiple returns occur from string-map, the values
3588returned by earlier returns are not mutated.
3589
3590 (string-map char-foldcase "AbdEgH") ==> "abdegh"
3591
3592 (string-map
3593 (lambda (c)
3594 (integer->char (+ 1 (char->integer c))))
3595 "HAL") ==> "IBM"
3596
3597 (string-map
3598 (lambda (c k)
3599 ((if (eqv? k #\u) char-upcase char-downcase)
3600 c))
3601 "studlycaps xxx"
3602 "ululululul") ==> "StUdLyCaPs"
3603
3604<procedure>(vector-map proc vector[1] vector[2] ...)</procedure>
3605
3606It is an error if proc does not accept as many arguments as there are vectors and return a single value.
3607
3608The vector-map procedure applies proc element-wise to the elements of the
3609vectors and returns a vector of the results, in order. If more than one
3610vector is given and not all vectors have the same length, vector-map terminates
3611when the shortest vector runs out. The dynamic order in which
3612proc is applied to the elements of the
3613vectors is unspecified. If multiple returns occur from vector-map, the values
3614returned by earlier returns are not mutated.
3615
3616 (vector-map cadr '#((a b) (d e) (g h)))
3617 ==> #(b e h)
3618
3619 (vector-map (lambda (n) (expt n n))
3620 '#(1 2 3 4 5))
3621 ==> #(1 4 27 256 3125)
3622
3623 (vector-map + '#(1 2 3) '#(4 5 6 7))
3624 ==> #(5 7 9)
3625
3626 (let ((count 0))
3627 (vector-map
3628 (lambda (ignored)
3629 (set! count (+ count 1))
3630 count)
3631 '#(a b))) ==> #(1 2) or #(2 1)
3632
3633<procedure>(for-each proc list[1] list[2] ...)</procedure><br>
3634
3635The arguments to for-each are like the arguments to map, but for-each
3636calls proc for its side effects rather than for its values. Unlike map,
3637for-each is guaranteed to call proc on the elements of the lists in
3638order from the first element(s) to the last, and the value returned by
3639for-each is unspecified.
3640
3641 (let ((v (make-vector 5)))
3642 (for-each (lambda (i)
3643 (vector-set! v i (* i i)))
3644 '(0 1 2 3 4))
3645 v) ===> #(0 1 4 9 16)
3646
3647Like in SRFI-1, this procedure allows the arguments to be of unequal
3648length; it terminates when the shortest list runs out. This is a
3649CHICKEN extension to R7RS.
3650
3651<procedure>(string-for-each proc string[1] string[2] ...)</procedure>
3652
3653It is an error if proc does not accept as many arguments as there are strings.
3654The arguments to string-for-each are like the arguments to string-map, but
3655string-for-each calls
3656proc for its side effects rather than for its values. Unlike string-map,
3657string-for-each is guaranteed to call
3658proc on the elements of the
3659strings in order from the first element(s) to the last, and the value returned
3660by string-for-each is unspecified. If more than one
3661string is given and not all strings have the same length, string-for-each
3662terminates when the shortest string runs out. It is an error for
3663proc to mutate any of the strings.
3664
3665 (let ((v '()))
3666 (string-for-each
3667 (lambda (c) (set! v (cons (char->integer c) v)))
3668 "abcde")
3669 v) ==> (101 100 99 98 97)
3670
3671<procedure>(vector-for-each proc vector[1] vector[2] ...)</procedure>
3672
3673It is an error if proc does not accept as many arguments as there are vectors.
3674The arguments to vector-for-each are like the arguments to vector-map, but
3675vector-for-each calls
3676proc for its side effects rather than for its values. Unlike vector-map,
3677vector-for-each is guaranteed to call
3678proc on the elements of the
3679vectors in order from the first element(s) to the last, and the value returned
3680by vector-for-each is unspecified. If more than one
3681vector is given and not all vectors have the same length, vector-for-each
3682terminates when the shortest vector runs out. It is an error for
3683proc to mutate any of the vectors.
3684
3685 (let ((v (make-list 5)))
3686 (vector-for-each
3687 (lambda (i) (list-set! v i (* i i)))
3688 '#(0 1 2 3 4))
3689 v) ==> (0 1 4 9 16)
3690
3691<procedure>(call-with-current-continuation proc)</procedure><br>
3692<procedure>(call/cc proc)</procedure><br>
3693
3694Proc must be a procedure of one argument. The procedure
3695call-with-current-continuation packages up the current continuation
3696(see the rationale below) as an "escape procedure" and passes it as
3697an argument to proc. The escape procedure is a Scheme procedure that,
3698if it is later called, will abandon whatever continuation is in effect
3699at that later time and will instead use the continuation that was in
3700effect when the escape procedure was created. Calling the escape
3701procedure may cause the invocation of before and after thunks installed
3702using dynamic-wind.
3703
3704The escape procedure accepts the same number of arguments as the
3705continuation to the original call to call-with-current-continuation.
3706Except for continuations created by the call-with-values procedure, all
3707continuations take exactly one value. The effect of passing no value or
3708more than one value to continuations that were not created by
3709call-with-values is unspecified.
3710
3711The escape procedure that is passed to proc has unlimited extent just
3712like any other procedure in Scheme. It may be stored in variables or
3713data structures and may be called as many times as desired.
3714
3715The following examples show only the most common ways in which
3716call-with-current-continuation is used. If all real uses were as simple
3717as these examples, there would be no need for a procedure with the
3718power of call-with-current-continuation.
3719
3720 (call-with-current-continuation
3721 (lambda (exit)
3722 (for-each (lambda (x)
3723 (if (negative? x)
3724 (exit x)))
3725 '(54 0 37 -3 245 19))
3726 #t)) ===> -3
3727
3728 (define list-length
3729 (lambda (obj)
3730 (call-with-current-continuation
3731 (lambda (return)
3732 (letrec ((r
3733 (lambda (obj)
3734 (cond ((null? obj) 0)
3735 ((pair? obj)
3736 (+ (r (cdr obj)) 1))
3737 (else (return #f))))))
3738 (r obj))))))
3739
3740 (list-length '(1 2 3 4)) ===> 4
3741
3742 (list-length '(a b . c)) ===> #f
3743
3744Rationale:
3745
3746A common use of call-with-current-continuation is for structured,
3747non-local exits from loops or procedure bodies, but in fact
3748call-with-current-continuation is extremely useful for implementing
3749a wide variety of advanced control structures.
3750
3751Whenever a Scheme expression is evaluated there is a continuation
3752wanting the result of the expression. The continuation represents
3753an entire (default) future for the computation. If the expression
3754is evaluated at top level, for example, then the continuation might
3755take the result, print it on the screen, prompt for the next input,
3756evaluate it, and so on forever. Most of the time the continuation
3757includes actions specified by user code, as in a continuation that
3758will take the result, multiply it by the value stored in a local
3759variable, add seven, and give the answer to the top level
3760continuation to be printed. Normally these ubiquitous continuations
3761are hidden behind the scenes and programmers do not think much
3762about them. On rare occasions, however, a programmer may need to
3763deal with continuations explicitly. Call-with-current-continuation
3764allows Scheme programmers to do that by creating a procedure that
3765acts just like the current continuation.
3766
3767Most programming languages incorporate one or more special-purpose
3768escape constructs with names like exit, return, or even goto. In
37691965, however, Peter Landin [16] invented a general purpose escape
3770operator called the J-operator. John Reynolds [24] described a
3771simpler but equally powerful construct in 1972. The catch special
3772form described by Sussman and Steele in the 1975 report on Scheme
3773is exactly the same as Reynolds's construct, though its name came
3774from a less general construct in MacLisp. Several Scheme
3775implementors noticed that the full power of the catch construct
3776could be provided by a procedure instead of by a special syntactic
3777construct, and the name call-with-current-continuation was coined
3778in 1982. This name is descriptive, but opinions differ on the
3779merits of such a long name, and some people use the name call/cc
3780instead.
3781
3782<procedure>(values obj ...)</procedure><br>
3783
3784Delivers all of its arguments to its continuation. Except for
3785continuations created by the call-with-values procedure, all
3786continuations take exactly one value. Values might be defined as
3787follows:
3788
3789 (define (values . things)
3790 (call-with-current-continuation
3791 (lambda (cont) (apply cont things))))
3792
3793<procedure>(call-with-values producer consumer)</procedure><br>
3794
3795Calls its producer argument with no values and a continuation that,
3796when passed some values, calls the consumer procedure with those values
3797as arguments. The continuation for the call to consumer is the
3798continuation of the call to call-with-values.
3799
3800 (call-with-values (lambda () (values 4 5))
3801 (lambda (a b) b))
3802 ===> 5
3803
3804 (call-with-values * -) ===> -1
3805
3806<procedure>(dynamic-wind before thunk after)</procedure><br>
3807
3808Calls thunk without arguments, returning the result(s) of this call.
3809Before and after are called, also without arguments, as required by the
3810following rules (note that in the absence of calls to continuations
3811captured using call-with-current-continuation the three arguments are
3812called once each, in order). Before is called whenever execution enters
3813the dynamic extent of the call to thunk and after is called whenever it
3814exits that dynamic extent. The dynamic extent of a procedure call is
3815the period between when the call is initiated and when it returns. In
3816Scheme, because of call-with-current-continuation, the dynamic extent
3817of a call may not be a single, connected time period. It is defined as
3818follows:
3819
3820* The dynamic extent is entered when execution of the body of the
3821 called procedure begins.
3822
3823* The dynamic extent is also entered when execution is not within the
3824 dynamic extent and a continuation is invoked that was captured
3825 (using call-with-current-continuation) during the dynamic extent.
3826
3827* It is exited when the called procedure returns.
3828
3829* It is also exited when execution is within the dynamic extent and a
3830 continuation is invoked that was captured while not within the
3831 dynamic extent.
3832
3833If a second call to dynamic-wind occurs within the dynamic extent of
3834the call to thunk and then a continuation is invoked in such a way that
3835the afters from these two invocations of dynamic-wind are both to be
3836called, then the after associated with the second (inner) call to
3837dynamic-wind is called first.
3838
3839If a second call to dynamic-wind occurs within the dynamic extent of
3840the call to thunk and then a continuation is invoked in such a way that
3841the befores from these two invocations of dynamic-wind are both to be
3842called, then the before associated with the first (outer) call to
3843dynamic-wind is called first.
3844
3845If invoking a continuation requires calling the before from one call to
3846dynamic-wind and the after from another, then the after is called
3847first.
3848
3849The effect of using a captured continuation to enter or exit the
3850dynamic extent of a call to before or after is undefined. However,
3851in CHICKEN it is safe to do this, and they will execute in the outer
3852dynamic context of the {{dynamic-wind}} form.
3853
3854 (let ((path '())
3855 (c #f))
3856 (let ((add (lambda (s)
3857 (set! path (cons s path)))))
3858 (dynamic-wind
3859 (lambda () (add 'connect))
3860 (lambda ()
3861 (add (call-with-current-continuation
3862 (lambda (c0)
3863 (set! c c0)
3864 'talk1))))
3865 (lambda () (add 'disconnect)))
3866 (if (< (length path) 4)
3867 (c 'talk2)
3868 (reverse path))))
3869
3870 ===> (connect talk1 disconnect
3871 connect talk2 disconnect)
3872
3873=== Exceptions
3874
3875This section describes Scheme’s exception-handling and exception-raising
3876procedures.
3877
3878Exception handlers are one-argument procedures that determine the action the
3879program takes when an exceptional situation is signaled. The system implicitly
3880maintains a current exception handler in the dynamic environment.
3881
3882The program raises an exception by invoking the current exception handler,
3883passing it an object encapsulating information about the exception. Any
3884procedure accepting one argument can serve as an exception handler and any
3885object can be used to represent an exception.
3886
3887<procedure>(with-exception-handler handler thunk)</procedure>
3888
3889It is an error if handler does not accept one argument. It is also an error if
3890thunk does not accept zero arguments.
3891The with-exception-handler procedure returns the results of invoking
3892thunk.
3893Handler is installed as the current exception handler in the dynamic
3894environment used for the invocation of
3895thunk.
3896
3897 (call-with-current-continuation
3898 (lambda (k)
3899 (with-exception-handler
3900 (lambda (x)
3901 (display "condition: ")
3902 (write x)
3903 (newline)
3904 (k 'exception))
3905 (lambda ()
3906 (+ 1 (raise 'an-error))))))
3907 ==> exception and prints "condition: an-error"
3908
3909 (with-exception-handler
3910 (lambda (x)
3911 (display "something went wrong\n"))
3912 (lambda ()
3913 (+ 1 (raise 'an-error))))
3914
3915prints "something went wrong"
3916After printing, the second example then raises another exception.
3917
3918<procedure>(raise obj)</procedure>
3919
3920Raises an exception by invoking the current exception handler on
3921obj. The handler is called with the same dynamic environment as that of the
3922call to raise, except that the current exception handler is the one that was in
3923place when the handler being called was installed. If the handler returns, a
3924secondary exception is raised in the same dynamic environment as the handler.
3925The relationship between
3926obj and the object raised by the secondary exception is unspecified.
3927
3928<procedure>(raise-continuable obj)</procedure>
3929
3930Raises an exception by invoking the current exception handler on
3931obj. The handler is called with the same dynamic environment as the call to
3932raise-continuable, except that: (1) the current exception handler is the one
3933that was in place when the handler being called was installed, and (2) if the
3934handler being called returns, then it will again become the current exception
3935handler. If the handler returns, the values it returns become the values
3936returned by the call to raise-continuable.
3937
3938 (with-exception-handler
3939 (lambda (con)
3940 (cond
3941 ((string? con)
3942 (display con))
3943 (else
3944 (display "a warning has been issued")))
3945 42)
3946 (lambda ()
3947 (+ (raise-continuable "should be a number")
3948 23)))
3949 prints: "should be a number"
3950 ==> 65
3951
3952<procedure>(error [location] message obj ...)</procedure>
3953
3954Message should be a string.
3955Raises an exception as if by calling raise on a newly allocated
3956implementation-defined object which encapsulates the information provided by
3957message, as well as any
3958objs, known as the irritants. The procedure error-object? must return #t on
3959such objects.
3960
3961 (define (null-list? l)
3962 (cond ((pair? l) #f)
3963 ((null? l) #t)
3964 (else
3965 (error
3966 "null-list?: argument out of domain"
3967 l))))
3968
3969If location is given and a symbol, it indicates the name of the procedure where
3970the error occurred.
3971
3972<procedure>(error-object? obj)</procedure>
3973
3974Returns #t if
3975obj is an object created by error or one of an implementation-defined set of
3976objects. Otherwise, it returns #f. The objects used to signal errors, including
3977those which satisfy the predicates file-error? and read-error?, may or may not
3978satisfy error-object?.
3979
3980<procedure>(error-object-message error-object)</procedure>
3981
3982Returns the message encapsulated by
3983error-object.
3984
3985<procedure>(error-object-irritants error-object)</procedure>
3986
3987Returns a list of the irritants encapsulated by
3988error-object.
3989
3990<procedure>(read-error? obj)</procedure><br>
3991<procedure>(file-error? obj)</procedure>
3992
3993Error type predicates. Returns #t if
3994obj is an object raised by the read procedure or by the inability to open an
3995input or output port on a file, respectively. Otherwise, it returns #f.
3996
3997=== Eval
3998
3999<procedure>(eval expression [environment-specifier])</procedure><br>
4000
4001Evaluates expression in the specified environment and returns its
4002value. Expression must be a valid Scheme expression represented as
4003data, and environment-specifier must be a value returned by one of the
4004three procedures described below. Implementations may extend eval to
4005allow non-expression programs (definitions) as the first argument and
4006to allow other values as environments, with the restriction that eval
4007is not allowed to create new bindings in the environments associated
4008with null-environment or scheme-report-environment.
4009
4010 (eval '(* 7 3) (scheme-report-environment 5))
4011 ===> 21
4012
4013 (let ((f (eval '(lambda (f x) (f x x))
4014 (null-environment 5))))
4015 (f + 10))
4016 ===> 20
4017
4018The {{environment-specifier}} is optional, and if not provided it
4019defaults to the value of {{(interaction-environment)}}. This is a
4020CHICKEN extension to R7RS, which, though strictly nonportable, is very
4021common among Scheme implementations.
4022
4023=== Input and output
4024
4025==== Ports
4026
4027Ports represent input and output devices. To Scheme, an input port is a Scheme
4028object that can deliver data upon command, while an output port is a Scheme
4029object that can accept data.
4030
4031Different port types operate on different data. Scheme implementations are
4032required to support textual ports and binary ports, but may also provide other
4033port types.
4034
4035A textual port supports reading or writing of individual characters from or to
4036a backing store containing characters using read-char and write-char below, and
4037it supports operations defined in terms of characters, such as read and write.
4038
4039A binary port supports reading or writing of individual bytes from or to a
4040backing store containing bytes using read-u8 and write-u8 below, as well as
4041operations defined in terms of bytes. Whether the textual and binary port types
4042are disjoint is implementation-dependent.
4043
4044Ports can be used to access files, devices, and similar things on the host
4045system on which the Scheme program is running.
4046
4047<procedure>(call-with-port port proc)</procedure>
4048
4049It is an error if
4050proc does not accept one argument.
4051The call-with-port procedure calls
4052proc with
4053port as an argument. If
4054proc returns, then the port is closed automatically and the values yielded by
4055the
4056proc are returned. If
4057
4058proc does not return, then the port must not be closed automatically unless it
4059is possible to prove that the port will never again be used for a read or write
4060operation.
4061
4062 Rationale: Because Scheme’s escape procedures have unlimited extent, it is
4063 possible to escape from the current continuation but later to resume it. If
4064 implementations were permitted to close the port on any escape from the
4065 current continuation, then it would be impossible to write portable code
4066 using both call-with-current-continuation and call-with-port.
4067
4068Ports represent input and output devices. To Scheme, an input port is a
4069Scheme object that can deliver characters upon command, while an output
4070port is a Scheme object that can accept characters.
4071
4072<procedure>(input-port? obj)</procedure><br>
4073<procedure>(output-port? obj)</procedure><br>
4074<procedure>(textual-port? obj)</procedure><br>
4075<procedure>(binary-port? obj)</procedure><br>
4076<procedure>(port? obj)</procedure>
4077
4078These procedures return #t if
4079obj is an input port, output port, textual port, binary port, or any kind of
4080port, respectively. Otherwise they return #f.
4081
4082<procedure>(input-port-open? port)</procedure><br>
4083<procedure>(output-port-open? port)</procedure>
4084
4085Returns #t if
4086port is still open and capable of performing input or output, respectively, and
4087#f otherwise.
4088
4089<procedure>(current-input-port [port])</procedure><br>
4090<procedure>(current-output-port [port])</procedure><br>
4091<procedure>(current-error-port [port])</procedure><br>
4092
4093Returns the current default input, output or error port.
4094
4095If the optional {{port}} argument is passed, the current input or
4096output port is changed to the provided port. It can also be used with
4097{{parameterize}} to temporarily bind the port to another value. This
4098is a CHICKEN extension to the R7RS standard.
4099
4100Note that the default output port is not buffered. Use
4101[[Module (chicken port)#set-buffering-mode!|{{set-buffering-mode!}}]]
4102if you need a different behavior.
4103
4104<procedure>(open-input-file filename [mode ...])</procedure><br>
4105<procedure>(open-binary-input-file filename [mode ...])</procedure>
4106
4107Takes a string naming an existing file and returns an input port
4108capable of delivering textual or binary data from the file. If the file cannot be
4109opened, an error is signalled.
4110
4111Additional {{mode}} arguments can be passed in, which should be any of
4112the keywords {{#:text}} or {{#:binary}}. These indicate the mode in
4113which to open the file (this has an effect on non-UNIX platforms
4114only). The extra {{mode}} arguments are CHICKEN extensions to the
4115R7RS standard.
4116
4117<procedure>(close-port port)</procedure><br>
4118<procedure>(close-input-port port)</procedure><br>
4119<procedure>(close-output-port port)</procedure><br>
4120
4121Closes the resource associated with
4122port, rendering the
4123port incapable of delivering or accepting data. It is an error to apply the
4124last two procedures to a port which is not an input or output port,
4125respectively. Scheme implementations may provide ports which are simultaneously
4126input and output ports, such as sockets; the close-input-port and
4127close-output-port procedures can then be used to close the input and output
4128sides of the port independently.
4129
4130These routines have no effect if the port has already been closed.
4131
4132<procedure>(open-input-string string)</procedure>
4133
4134Takes a string and returns a textual input port that delivers characters from
4135the string. If the string is modified, the effect is unspecified.
4136
4137<procedure>(open-output-string)</procedure>
4138
4139Returns a textual output port that will accumulate characters for retrieval by
4140get-output-string.
4141
4142<procedure>(get-output-string port)</procedure>
4143
4144It is an error if
4145port was not created with open-output-string.
4146Returns a string consisting of the characters that have been output to the port
4147so far in the order they were output. If the result string is modified, the
4148effect is unspecified.
4149
4150 (parameterize
4151 ((current-output-port
4152 (open-output-string)))
4153 (display "piece")
4154 (display " by piece ")
4155 (display "by piece.")
4156 (newline)
4157 (get-output-string (current-output-port)))
4158 ==> "piece by piece by piece.\n"
4159
4160<procedure>(open-input-bytevector bytevector)</procedure>
4161
4162Takes a bytevector and returns a binary input port that delivers bytes from the
4163bytevector.
4164
4165<procedure>(open-output-bytevector)</procedure>
4166
4167Returns a binary output port that will accumulate bytes for retrieval by
4168get-output-bytevector.
4169
4170<procedure>(get-output-bytevector port)</procedure>
4171
4172It is an error if
4173port was not created with open-output-bytevector.
4174Returns a bytevector consisting of the bytes that have been output to the port
4175so far in the order they were output.
4176
4177==== Input
4178
4179If port is omitted from any input procedure, it defaults to the value returned by
4180(current-input-port). It is an error to attempt an input operation on a closed
4181port.
4182
4183<procedure>(read-char [port])</procedure><br>
4184
4185Returns the next character available from the input port, updating the
4186port to point to the following character. If no more characters are
4187available, an end of file object is returned. Port may be omitted, in
4188which case it defaults to the value returned by current-input-port.
4189
4190<procedure>(peek-char [port])</procedure><br>
4191
4192Returns the next character available from the input port, without
4193updating the port to point to the following character. If no more
4194characters are available, an end of file object is returned. Port may
4195be omitted, in which case it defaults to the value returned by
4196current-input-port.
4197
4198Note: The value returned by a call to peek-char is the same as
4199the value that would have been returned by a call to read-char with
4200the same port. The only difference is that the very next call to
4201read-char or peek-char on that port will return the value returned
4202by the preceding call to peek-char. In particular, a call to
4203peek-char on an interactive port will hang waiting for input
4204whenever a call to read-char would have hung.
4205
4206<procedure>(read-line [port])</procedure>
4207
4208Returns the next line of text available from the textual input
4209port, updating the
4210port to point to the following character. If an end of line is read, a string
4211containing all of the text up to (but not including) the end of line is
4212returned, and the port is updated to point just past the end of line. If an end
4213of file is encountered before any end of line is read, but some characters have
4214been read, a string containing those characters is returned. If an end of file
4215is encountered before any characters are read, an end-of-file object is
4216returned. For the purpose of this procedure, an end of line consists of either
4217a linefeed character, a carriage return character, or a sequence of a carriage
4218return character followed by a linefeed character. Implementations may also
4219recognize other end of line characters or sequences.
4220
4221<procedure>(eof-object? obj)</procedure><br>
4222
4223Returns #t if obj is an end of file object, otherwise returns #f. The
4224precise set of end of file objects will vary among implementations, but
4225in any case no end of file object will ever be an object that can be
4226read in using read.
4227
4228<procedure>(eof-object)</procedure>
4229
4230Returns an end-of-file object, not necessarily unique.
4231
4232<procedure>(char-ready? [port])</procedure><br>
4233
4234Returns #t if a character is ready on the input port and returns #f
4235otherwise. If char-ready returns #t then the next read-char operation
4236on the given port is guaranteed not to hang. If the port is at end of
4237file then char-ready? returns #t. Port may be omitted, in which case it
4238defaults to the value returned by current-input-port.
4239
4240Rationale: Char-ready? exists to make it possible for a program
4241to accept characters from interactive ports without getting stuck
4242waiting for input. Any input editors associated with such ports
4243must ensure that characters whose existence has been asserted by
4244char-ready? cannot be rubbed out. If char-ready? were to return #f
4245at end of file, a port at end of file would be indistinguishable
4246from an interactive port that has no ready characters.
4247
4248<procedure>(read-string k [port])</procedure>
4249
4250See [[Module (chicken io)|(chicken io) module]] for more information.
4251
4252<procedure>(read-u8 [port])</procedure>
4253
4254Returns the next byte available from the binary input
4255port, updating the
4256port to point to the following byte. If no more bytes are available, an
4257end-of-file object is returned.
4258
4259<procedure>(peek-u8 [port])</procedure>
4260
4261Returns the next byte available from the binary input
4262port, but without updating the
4263port to point to the following byte. If no more bytes are available, an
4264end-of-file object is returned.
4265
4266<procedure>(u8-ready? [port])</procedure>
4267
4268Returns #t if a byte is ready on the binary input
4269port and returns #f otherwise. If u8-ready? returns #t then the next read-u8
4270operation on the given
4271port is guaranteed not to hang. If the
4272port is at end of file then u8-ready? returns #t.
4273
4274<procedure>(read-bytevector k [port])</procedure><br>
4275<procedure>(read-bytevector! bytevector [port [start [end]]])</procedure>
4276
4277See [[Module (chicken io)|(chicken io) module]] for more information.
4278
4279==== Output
4280
4281If port is omitted from any output procedure, it defaults to the value returned by
4282(current-output-port). It is an error to attempt an output operation on a
4283closed port.
4284
4285<procedure>(newline)</procedure><br>
4286<procedure>(newline port)</procedure><br>
4287
4288Writes an end of line to port. Exactly how this is done differs from
4289one operating system to another. Returns an unspecified value. The port
4290argument may be omitted, in which case it defaults to the value
4291returned by current-output-port.
4292
4293<procedure>(write-char char)</procedure><br>
4294<procedure>(write-char char port)</procedure><br>
4295
4296Writes the character char (not an external representation of the
4297character) to the given port and returns an unspecified value. The port
4298argument may be omitted, in which case it defaults to the value
4299returned by current-output-port.
4300
4301<procedure>(write-string string [port [start [end]]])</procedurew>
4302
4303Writes the characters of
4304string from
4305start to
4306end in left-to-right order to the textual output
4307port.
4308
4309<procedure>(write-u8 byte [port])</procedure>
4310
4311Writes the
4312byte to the given binary output
4313port and returns an unspecified value.
4314
4315<procedure>(write-bytevector bytevector [port [start [end]]])</procedure>
4316
4317See [[Module (chicken bytevector)|The (chicken bytevector) module]] for more
4318information.
4319
4320<procedure>(flush-output-port [port])</procedure>
4321
4322Flushes any buffered output from the buffer of output-port to the underlying
4323file or device and returns an unspecified value.
4324
4325==== System interface
4326
4327Questions of system interface generally fall outside of the domain of
4328this report. However, the following operations are important enough to
4329deserve description here.
4330
4331<procedure>(features)</procedure>
4332
4333Returns a list of the feature identifiers which cond-expand treats as true. It
4334is an error to modify this list. Here is an example of what features might
4335return:
4336
4337 (features) ==>
4338 (r7rs ratios exact-complex full-unicode
4339 gnu-linux little-endian
4340 fantastic-scheme
4341 fantastic-scheme-1.0
4342 space-ship-control-system)
4343
4344---
4345Previous: [[Module scheme]]
4346
4347Next: [[Module (scheme case-lambda)]]